GoLand 2022.3 Help

Embedding files

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

Code completion

  • You can complete names of files and directories with auto-completion or by pressing Ctrl+Space.

    code_completion_for_embed_directive
  • To navigate from a reference to the corresponding file, press Ctrl+B.

    Navigation from references to files

Rename files and directories

  • Click the filename and navigate to Refactor | Rename.

    Rename files and directories

Find usages of a file

  • Click the filename and select Edit | Find Usages | Find Usages.

    Find usages of a file

Using inspections

The IDE will display a warning in the following situations.

  • You reference a file or folder that does not exist.

    folder that does not exist
  • You try to embed files in a struct type or any other unsupported type.

  • You forgot to add the embed package to your import list.

    The embed package is missing
Last modified: 12 December 2022