DEV Community

Cover image for Seamlessly Embed Files Into Your Go Binary
prakash chokalingam
prakash chokalingam

Posted on

Seamlessly Embed Files Into Your Go Binary

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")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
siwalikm profile image
Siwalik Mukherjee

Nice read Prakash, can go:embed be used to embed dynamic content generated during runtime?

Collapse
 
prakash_chokalingam profile image
prakash chokalingam

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.