How to embed files into Golang binaries?

后端 未结 7 1366
遇见更好的自我
遇见更好的自我 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: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

提交回复
热议问题