Incorporating YAML, JSON, or other configuration files into your Go application is becoming a standard practice, these files are often being referenced by file paths within the project. Although the go-build process completes smoothly, executing the standalone binary can result in a 'file not found' error. This means you have to keep these setting files close to your app wherever you run it.
To circumvent this issue, Go offers a powerful feature known as embed. This allows developers to include their files directly within the binary by creating an embedded file system.
Usage
import "embed"
//go:embed config.yaml
var embedFS embed.FS
# access config file
config, _ := embedFS.ReadFile("config.yaml")
You can even embed a list of directories as part of your go binary,
import "embed"
//go:embed templates/* config/*
var embedFS embed.FS
# access email template
template, _ := embedFS.ReadFile("templates/email.hbs")
This feature enables you to run the go binary standalone without any external dependencies.
For more details please check the go embed documentation.
Top comments (2)
Nice read Prakash, can go:embed be used to embed dynamic content generated during runtime?
I don't think so @siwalikm, We can't write files within the embed fs dynamically, It can be used only to read. You can utilize the actual file system (pkg.go.dev/os) to read and write files dynamically.