How to embed files into Golang binaries?

后端 未结 7 1331
遇见更好的自我
遇见更好的自我 2020-12-12 16:58

I have some text file that I read from my Go program. I\'d like to ship a single executable, without supplying that text file additionally. How do I embed it into compilatio

相关标签:
7条回答
  • 2020-12-12 17:38

    I used a simple function to read an external template in a go generate run and to generate Go code from it. A function returning the template as a string will be generated. One can then parse the returned template string using tpl, err := template.New("myname").Parse(mynameTemplate())

    I did put that code to github. You might want to try https://github.com/wlbr/templify

    Very simple, but works for me quite well.

    0 讨论(0)
  • 2020-12-12 17:41

    Use go-bindata. From the README:

    This tool converts any file into managable Go source code. Useful for embedding binary data into a go program. The file data is optionally gzip compressed before being converted to a raw byte slice.

    0 讨论(0)
  • 2020-12-12 17:41

    Based on @CoreyOgburn comment and this Github comment, the following snippet was created:

    //go:generate statik -src=./html
    
    package main
    
    import (
        _ "./statik"
        "github.com/rakyll/statik/fs"
    )
    
    func statikFile() {
        s, _ := fs.New()
        f, _ := s.Open("/tmpl/login.html")
        b, _ := ioutil.ReadAll(f)
        t, _ := template.New("login").Parse(string(b))
        t.Execute(w, nil)
    }
    

    and run

    go generate
    

    and subsequently

    go build
    

    should create a binary that contains the files

    0 讨论(0)
  • 2020-12-12 17:47

    check packr, its quite friendly to use

    package main
    
    import (
      "net/http"
    
      "github.com/gobuffalo/packr"
    )
    
    func main() {
      box := packr.NewBox("./templates")
    
      http.Handle("/", http.FileServer(box))
      http.ListenAndServe(":3000", nil)
    }
    
    0 讨论(0)
  • 2020-12-12 17:51

    You can use a string literal to define the text as a constant or variable. String literals are defined by enclosing the string with back-quotes. e.g. `string`.

    For example:

    package main
    
    import "fmt"
    
    func main() {
        const text = `
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit  
    amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante 
    hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet 
    vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut 
    libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, 
    consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a 
    semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. 
    Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut 
    convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis 
    quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis 
    parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae 
    nisi at sem facilisis semper ac in est.
    `
    
        fmt.Println(text)
    }
    
    0 讨论(0)
  • 2020-12-12 17:53

    Was looking for the same thing and came across esc: Embedding Static Assets in Go (by 19 Nov 2014) where author, Matt Jibson, is evaluating 3 other popular packages that claims to do file embedding:

    1. rakyll/statik
    2. jteeuwen/go-bindata (and the new official go-bindata/go-bindata and another improved one kevinburke/go-bindata)
    3. GeertJohan/go.rice

    and explain why he eventually come up with his own package:

    1. mjibson/esc

    So after briefly trying them all (in that order) I've naturally settled on Matt's esc as it was the only one that was working out of the box with necessary for me functionality, namely:

    1. Can take some directories and recursively embed all files in them in a way that was compatible with http.FileSystem
    2. Can optionally be disabled for use with the local file system for local development without changing the client's code
    3. Will not change the output file on subsequent runs has reasonable-sized diffs when files changed
    4. Capable of doing the work via //go:generate instead of forcing you to manually write additional Go code

    The point #2 was important for me and the rest of the packages for one reason or another didn't work out that well.

    From esc's README:

    esc embeds files into go programs and provides http.FileSystem interfaces to them.

    It adds all named files or files recursively under named directories at the path specified. The output file provides an http.FileSystem interface with zero dependencies on packages outside the standard library.

    0 讨论(0)
提交回复
热议问题