typestar

Embedding files in Go

go:embed puts files into the binary at compile time.

package assets

import "embed"

//go:embed schema.sql
var Schema string

//go:embed static
var Files embed.FS

// Read returns one embedded file's contents.
func Read(name string) ([]byte, error) {
    return Files.ReadFile("static/" + name)
}

How it works

  1. The directive sits directly above the variable it fills.
  2. A string, a []byte or an embed.FS are the three targets.
  3. The files must live in or under the package directory.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
239
Tokens
39
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 22 seconds.

Type this snippet

Step 4 of 5 in Packages & build, step 24 of 26 in Standard library & project layout.

← Previous Next →