liveBook · Manning

Go:embed directive

As explained in Learn Go with Pocket-Sized Projects

go:embed is a Go compiler directive that embeds the contents of files into variables during compilation.

The //go:embed directive puts file contents into a global Go variable at compilation. It is useful for templates that do not change between runs, without reading them from disk each time they are needed. section 11.1.2

package server

import (
  _ "embed" // Allows us to load files
  ...
)

//go:embed index.html // Load the file contents to the indexPage variable.
var indexPage string

This excerpt embeds index.html in a string. The underscore import makes the embed package available to the directive without calling its functions or types. section 11.1.2

Pass the embedded string to template.New("index").Parse(indexPage), then execute the parsed template with a value. Handle parsing and execution errors; a malformed template provides a way to test the error path. section 11.1.2

Listing 11.46 index.html: Embedding the contents of a directory
//go:embed templates/*.html #1
var templates embed.FS

...
tpl, err := template.New("index").Funcs(template.FuncMap{
    "statusCSSClass": statusCSSClass,
    "progress":       progress,
}).ParseFS(templates, "templates/*.html") #2

For several files, this fragment embeds matching HTML templates in a read-only embed.FS and loads them with ParseFS. section 11.5.3 section 11.6

After loading multiple templates, execute the desired one by name, such as ExecuteTemplate(w, "index.html", data). Embedding also avoids opening the current on-disk template contents on every endpoint call, which could expose the application to malicious changes. section 11.5.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Demonstrates string and filesystem embedding with template parsing, without detailing compiler internals or the full pattern rules.
Examples
Embeds an HTML index page, a set of HTML templates, and a CSS template.
What you can do after
Apply it via Go's embed package to load template files as a string or read-only filesystem.
How it connects
Connects file embedding to HTML templates, text templates, filesystem access, and template execution.

Also explained in

Compare how 2 books explain go:embed directive →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.