GoLand
 
Get GoLand

Embedding files

Last modified: 11 October 2024

Starting with Go 1.16, you can embed files into your Go binaries. It means that you can build and ship to your users a binary that already has all the necessary files from your hard drive. So, there is no need to ship them separately and place them at a certain location on the computer. And the next time you move the binary to another directory, you do not need to update the paths to these files.

Moreover, consider the following usages:

  • You can embed template files while working with Go templates

  • Ship HTML, CSS, and JavaScript files along with a Go server binary

  • Ship database migration scripts with a binary

To embed files, you need to use the //go:embed directive and specify a file or files that you want to embed. You must declare these variables at the top level of a package. It means that function bodies cannot contain these variables.

You can embed the following types: string, []byte, and embed.FS.

If you embed a directory, then all files beginning with dots (.) or underscores (_) are excluded. To include them, you need to use the all prefix. For example, all:webapp embeds ‘webapp/.tempfile’ and ‘webapp/dir/.tempfile’.

Embedding files in Go