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.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works from a single embedded string through multi-file `embed.FS` parsing and named execution, without detailing compiler internals.
Examples
Uses an embedded `index.html`, a `templates/*.html` filesystem, and an embedded `styles.css` with color values.
What it assumes
Builds on Go imports, package variables, and HTTP handlers while introducing embedding through a first HTML template.
What you can do after
Apply it via `//go:embed` to load single-file or multi-file templates and handle parsing and execution errors.
How it connects
Connects package-level variables and imports with `embed.FS`, `html/template`, `text/template`, and HTTP handlers.

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.