Skip to Content
Course content

208: Embedding Files with go:embed

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're selling a high-end board game. You could give the customer the game board and the pieces, but then include a note saying, "To actually play, please go to the hardware store and buy a specific set of 12 dice." That's a terrible user experience. The customer might buy the wrong dice, or the store might be closed, or they might just lose the dice before the first game night. The better way? You put the dice right inside the box. The game is self-contained; everything needed to run the experience is shipped as a single unit.

In Go, we often do the "hardware store" approach. We write code that looks for a config.json or an index.html file on the hard drive at runtime. It works on your machine, but the moment you deploy it to a server or send the binary to a teammate, the app crashes because the binary can't find the files in the expected relative path. go:embed is how we put the dice in the box. It lets us bake static assets directly into the compiled binary.

Stopping the "File Not Found" Hunt

Before go:embed arrived, we had to rely on os.ReadFile. I can't tell you how many hours I've wasted debugging open templates/index.html: no such file or directory just because I ran the program from the project root instead of the /bin folder. It's a headache.

With embedding, we tell the compiler: "When you build this binary, grab the contents of this specific file and store them in this variable." Here is how you handle a single file, like a version text file or a small SQL schema:

package main

import (
	_ "embed"
	"fmt"
)

//go:embed version.txt
var Version string

func main() {
	fmt.Printf("Running App Version: %s\n", Version)
}

Notice that //go:embed version.txt isn't actually a comment to the Go compiler—it's a directive. The Version variable is populated at compile time. When you ship the binary, version.txt doesn't need to travel with it; it's already inside.

Packing Entire Folders with embed.FS

Usually, you aren't just embedding one file. You've probably got a whole static/ folder full of CSS, JS, and images. You don't want to declare fifty different variables. This is where embed.FS (an embedded file system) comes in. It gives you a read-only virtual filesystem that behaves a lot like the standard os package.

I personally love using this for web servers. Instead of fighting with http.FileServer and relative paths on a Linux server, you can do this:

package main

import (
	"embed"
	"net/http"
)

//go:embed static/*
var staticFiles embed.FS

func main() {
	// We wrap the embedded FS to strip the "static/" prefix from the URL
	fs := http.FileServer(http.FS(staticFiles))
	
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	http.ListenAndServe(":8080", nil)
}

By using embed.FS, your entire frontend is now a part of the executable. You can move that binary to any machine in the world, and as long as it can open a network port, your website will load perfectly.

The Trade-offs You Should Know

Now, it's not all magic. There are a couple of things to keep in mind. First, embedded files are read-only. You can't use go:embed to load a config file that you intend to let the user edit and save while the app is running. If you need read/write access, you're back to using os.Open.

Second, be mindful of binary size. I once saw a developer embed a 500MB machine learning model into a Go binary. It worked, but the compile times became glacial and the resulting binary was a monster. For massive files, stick to external storage or cloud buckets. For templates, configs, and small assets? Embed them every single time.




📋 Practical Task

Building a Self-Contained Email Template Server

You are building a microservice that sends branded emails. Instead of relying on the server's local filesystem to find the HTML templates, you need to bake them into the binary to ensure the service is portable across different environments.

Requirements:

  • Create a folder named templates in your project root.
  • Inside templates, create two files: welcome.html and goodbye.html (put some basic HTML content in them).
  • In your main.go file, use embed.FS to embed the entire templates directory.
  • Write a function GetTemplate(name string) (string, error) that takes a filename (e.g., "welcome.html") and returns the contents of that file as a string using the ReadFile method of the embedded filesystem.
  • In main, call this function for both files and print their contents to the console to verify they were successfully embedded.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.