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

