Embedding Files into Go Binaries
In programming, it is common to distribute executable files that require additional resources, such as text files. To simplify deployment and avoid having to distribute multiple files, it is beneficial to embed these resources within the binary itself.
Embedding Files with go:embed (Go 1.16 and later)
With Go 1.16, the go:embed directive provides a straightforward method for embedding files:
package main import "embed" // Embed the "hello.txt" file as a string //go:embed hello.txt var s string // Embed the "hello.txt" file as a byte slice //go:embed hello.txt var b []byte // Embed the "hello.txt" file as an embed.FS object //go:embed hello.txt var f embed.FS func main() { // Read the file contents as a string data, _ := f.ReadFile("hello.txt") println(string(data)) }
Embedding Files with go generate (Before Go 1.16)
For earlier versions of Go, go generate offers an alternative approach:
Example code:
main.go
package main import "fmt" //go:generate go run scripts/includetxt.go func main() { fmt.Println(a) fmt.Println(b) }
scripts/includetxt.go
package main import ( "io" "io/ioutil" "os" "strings" ) // Embed all .txt files as string literals func main() { fs, _ := ioutil.ReadDir(".") out, _ := os.Create("textfiles.go") for _, f := range fs { if strings.HasSuffix(f.Name(), ".txt") { out.WriteString(strings.TrimSuffix(f.Name(), ".txt") + " = `") f, _ := os.Open(f.Name()) io.Copy(out, f) out.WriteString("`\n") } } }
Compilation:
$ go generate $ go build -o main
Additional Notes:
The above is the detailed content of How Can I Embed Files into Go Binaries Using `go:embed` and `go generate`?. For more information, please follow other related articles on the PHP Chinese website!