How to Use //go:embed
Update: Want to listen to a podcast about go:embed instead of reading a blog post? Check out Go Time episode 171.
I have previously written about how to use //go:generate
. It exists to “to automate the running of tools to generate source code before compilation.” Now there is a new feature in Go that eliminates many uses of source code generation. In addition to the remarkable new flag.Func feature, Go 1.16 also introduced a new //go:embed
directive that allows you to include the contents of arbitrary files and directories in your Go application. To demonstrate some of the capabilities of //go:embed
, I have made an example repo which I will explain in this post.
The basic idea of embedding is that by adding a special comment to your code, Go will know to include a file or files. The comment should look like //go:embed FILENAME(S)
and be followed by a variable of the type you want to embed: string
or []byte
for an individual file or embed.FS
for a group of files. The go:embed
directive understands Go file globs, so patterns like files/*.html
will also work (but not **/*.html
recursive globbing).
You can read the official docs for a complete technical explanation, so here let’s take a look at some examples to see what’s possible.