Use `//go:embed` when a Go program needs a file whose contents should be captured at compilation rather than read from disk on each request. A common case is a template kept in its own file instead of inside Go source code. section 11.1.2 section 11.6
package server import ( _ "embed" // Allows us to load files ... ) //go:embed index.html // Load the file contents to the indexPage variable. var indexPage string
Place the directive immediately above a package-level variable. For a string variable, import `embed` with a blank identifier because no package name is used directly. section 11.1.2
Pass the embedded string to `template.New("index").Parse(indexPage)`, then execute the template with data. A malformed template can make parsing fail, so handle and log the error. Unlike opening the file on each request, embedding prevents later changes to the on-disk template from changing what the endpoint reads. section 11.1.2 section 11.5.3
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 multiple HTML files, embed the `templates/*.html` pattern into an `embed.FS` and load it with `ParseFS`. When parsing several named templates, execute the intended one by name—for example, `index.html`—rather than an empty template named `index`. section 11.5.3
An embedded CSS template
A stylesheet can use the same single-file pattern: embed `templates/styles.css` into a string, parse it with `text/template`, and execute it with color values. Set the response content type to `text/css`. section 11.5.3

