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 compilation on Windows and Linux?
相关问题
- Golang mongodb aggregation
- How to flatten out a nested json structure in go
- how to install private repo using glide golang
- How to convert a string to a byte array which is c
- IntelliJ 2017.1.2 GOLANG debug does not work on br
check packr, its quite friendly to use
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 usingtpl, 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.
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:
and explain why he eventually come up with his own package:
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:
//go:generate
instead of forcing you to manually write additional Go codeThe 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:
Based on @CoreyOgburn comment and this Github comment, the following snippet was created:
and run
and subsequently
should create a binary that contains the files
Since Go 1.4, you can use go generate if you need more flexibility.
If you have more than one text file or the text file may change you might not want to hardcode the text file but include it at compile time.
If you have the following files:
And want to have access to the contents of all .txt files in main.go, you can include a special comment containing a go generate command.
main.go
The go generate command will run the script after
go:generate
. In this case it runs a go script which reads all text files and outputs them as string literals into a new file. I skipped the error handling for shorter code.script/includetxt.go
To compile all .txt files into your exectutable:
Now your directory structure will look like:
Where textfiles.go was generated by go generate and script/includetxt.go
textfiles.go
And running main gives
This will work fine as long as you're encoding UTF8 encoded files. If you want to encode other files you have the full power of the go language (or any other tool) to do so. I used this technique to hex encode png:s into a single executable. That requires a minor change to includetxt.go.
Use go-bindata. From the README: