Incorporating Files into Go Binaries
Want to distribute a single executable that includes necessary text files? Go provides solutions for embedding files into binaries, tailored for various platforms.
Go 1.16 and Beyond: go:embed Directive
For Go versions 1.16 and higher, leverage the go:embed directive. It offers an elegant way to embed files:
import "embed" //go:embed hello.txt var s string print(s) //go:embed hello.txt var b []byte print(string(b)) //go:embed hello.txt var f embed.FS data, _ := f.ReadFile("hello.txt") print(string(data))
Go 1.4 and Later: go generate for Flexibility
For Go versions 1.4 and onward, you can resort to go generate for greater flexibility. This approach involves:
This technique enables embedding multiple text files with minimal hardcoding. For instance:
main.go
package main import "fmt" //go:generate go run scripts/includetxt.go func main() { fmt.Println(a) fmt.Println(b) }
script/includetxt.go
package main import ( "io" "io/ioutil" "os" "strings" ) func main() { fs, _ := ioutil.ReadDir(".") out, _ := os.Create("textfiles.go") out.Write([]byte("package main \n\nconst (\n")) for _, f := range fs { if strings.HasSuffix(f.Name(), ".txt") { out.Write([]byte(strings.TrimSuffix(f.Name(), ".txt") + " = `")) f, _ := os.Open(f.Name()) io.Copy(out, f) out.Write([]byte("`\n")) } } out.Write([]byte(")\n")) }
Build Commands:
$ go generate $ go build -o main
The above is the detailed content of How Can I Embed Files into My Go Binaries?. For more information, please follow other related articles on the PHP Chinese website!