One of the features that I like the most about Go compared to other langages is how easy distribution of binaries can be.
Go statically links most dependancies by default, meaning that typically just one binary is requried for your program to run.
However most programs have text or images embedded in them, and pull these resources in at runtime. If these exact same resources are always going to be pulled into your program at runtime, you're not saving any memory, disk space or network usage by opening them on program startup. Instead, you can speed up your whole program, and simplify app deployment, but directly embedding these resources.
Previously I use go Packr to handle this, but now Go has built in support for embedding that is amazing!
To embed the content of ./hello.txt
Just import _ "embed"
and use the special //go:embed <filename>
comment on the line before your variable is initialized:
package content
import _ "embed"
//go:embed hello.txt
var Hello string
Then in other parts of your program, you can just fmt.Println(content.Hello)
, and you've saved youself from slowly opening a file on disk, handling errors when the file doesn't load, and now your binary doesn't need to depend on these files!
You can even use wildcards and embed a whole virtual filesystem:
//go:embed image/*
//go:embed html/index.html
var content embed.FS
and then later serve up that filesystem with:
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(content))))
You may want to refer to the documentation at: