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
- The directive sits directly above the variable it fills.
- A string, a []byte or an embed.FS are the three targets.
- The files must live in or under the package directory.
Keywords and builtins used here
byteerrorfuncreturnstringvar
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.
Step 4 of 5 in Packages & build, step 24 of 26 in Standard library & project layout.