DEV Community

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

Posted on

8

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay