embed
package allows you to embed static files or strings directly into your Go binaries. This feature is particularly useful for embedding assets like HTML, CSS, JavaScript files, or configuration files without requiring external dependencies at runtime.
In Go, the embed package allows you to embed static files or strings directly into your Go binaries. This feature is particularly useful for embedding assets like HTML, CSS, JavaScript files, or configuration files without requiring external dependencies at runtime.
Here’s how to use embed:
1. Import the embed Package
To use the embed package, import it in your code:
go
Copy code
import _ "embed"
2. Declare a Variable for the Embedded Data
Use Go comments to specify the file or files you want to embed. Place the //go:embed directive above the variable declaration.
Embedding a Single File
To embed a single file as a string or []byte:
go
Copy code
import (
"embed"
"fmt"
)
//go:embed example.txt
var fileContent string
func main() {
fmt.Println("File content:")
fmt.Println(fileContent)
}
Embedding a Directory
To embed multiple files in a directory:
go
Copy code
//go:embed assets/*
var assets embed.FS
func main() {
data, err := assets.ReadFile("assets/example.txt")
if err != nil {
panic(err)
}
fmt.Println(string(data))
}
Important Notes
- The
//go:embed
directive must be placed directly above the variable declaration. - Embedded files or directories must exist when the program is compiled; otherwise, the build will fail.
assets/*
matches all files directly inside theassets/
directory.- It does not include files in subdirectories. If you want to include subdirectories and their contents, you can use
assets/**
.
Embedding into the Binary:
- The specified files are embedded into the Go binary at compile time.
- These files become part of the executable and do not
//go:embed
directive is always relative to the Go source file containing the directive.cmd/main.go
and you want to embed a folder assets
located in the project root, use the relative path ../assets/*
.Folder Existence:
- The folder and the files within it must exist at compile time. If they do not exist, the build will fail.
Absolute Paths:
- Absolute paths are not allowed. The path must be relative to the Go source file.
Examples:
- Folder in the Current Directory:
- Folder in a Parent Directory:
- Folder in a Subdirectory:
No comments:
Post a Comment