Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
208: Embedding Files with go:embed
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
templatesin your project root. - Inside
templates, create two files:welcome.htmlandgoodbye.html(put some basic HTML content in them). - In your
main.gofile, useembed.FSto embed the entiretemplatesdirectory. - 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 theReadFilemethod 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.
There are no comments for now.