Go

embed — Compile Assets into the Binary

admin by @admin ADMIN
Jun 19, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Go 1.16+ `embed` lets you bundle static files (templates, web assets, SQL migrations) directly into the compiled binary — no companion files to ship.
Go
Raw
package main

import (
    "embed"
    "fmt"
    "io/fs"
    "net/http"
)

// Embed a single file
//go:embed version.txt
var version string                              // file contents as a string

// Embed many files into a virtual filesystem
//go:embed assets/*
var assets embed.FS

// Embed templates with pattern matching
//go:embed templates/*.html
var templates embed.FS

func main() {
    fmt.Println("version:", version)

    // Use the FS for an http.FileServer
    sub, _ := fs.Sub(assets, "assets")           // strip the "assets/" prefix
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(sub))))

    // Read a file from the embedded FS
    data, _ := assets.ReadFile("assets/logo.png")
    fmt.Println("logo size:", len(data))

    http.ListenAndServe(":8080", nil)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.