liveBook · Manning

Go:embed directive

As explained in Go by Example

File embedding is the Go compiler feature that incorporates external file contents into a program's variables and compiled binary.

File embedding places an external file’s contents in a variable and the compiled binary. Keeping SQL in schema.sql preserves editor highlighting and lets a deployed program run without a separate schema file. section 10.1.3

Embed and apply a database schema

Import embed for its compiler-activation side effect, declare the directive, then pass the resulting string to the database: import ( _ "embed" ) //go:embed schema.sql var schema string func Dial(ctx context.Context, dsn string) (*sql.DB, error) { db, err := sql.Open("sqlite", dsn) if err != nil { return nil, fmt.Errorf("opening: %w", err) } if err := db.PingContext(ctx); err != nil { return nil, fmt.Errorf("pinging: %w", err) } if _, err := db.ExecContext(ctx, schema); err != nil { return nil, fmt.Errorf("applying schema: %w", err) } return db, nil } section 10.1.3

//go:embed *.sql  #1
var schemaFiles embed.FS  #2
. . .
files, err := schemaFiles.ReadDir(".") #3
. . .
for _, schema := range files {  #4
    . . .  #5
}

Use an embedded embed.FS when a package needs to include multiple matching files, enumerate them, and process each file at runtime. section 10.1.3

Keep the implementation predictable:

  • Use a blank embed import when the program only needs the compiler feature, not an exported package symbol. section 10.1.3
  • Distribute the compiled binary without additional embedded resource files. section 10.1.3 section 10.6

How Go by Example covers it

How deep it goes
Explains compiler embedding, blank-import activation, string variables, embed.FS, and runtime database execution.
Examples
Uses a SQLite schema.sql file, a string variable, DB.ExecContext, and an embed.FS pattern for multiple SQL files.
What it assumes
Assumes familiarity with Go packages, variables, SQL, databases, and context-aware methods; teaches embedding activation from the implementation.
What you can do after
Operate/configure deployments by embedding schemas and executing them without distributing separate SQL files.
How it connects
Connects file embedding with SQL schemas, compiled binaries, embed.FS, SQLite, and database initialization.

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 Go by Example. The section links point to the parts of the book it draws on.