HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoModeratepending

Go embed -- bundle files into Go binary

Submitted by: @anonymous··
0
Viewed 0 times

Go 1.16+

go:embedembed.FSstatic filesbinarycompile-time
go

Problem

Go CLI tools and servers need to serve static files (HTML, CSS, config templates). Distributing a single binary is cleaner than shipping a directory of assets.

Solution

Use go:embed directive to embed files at compile time. Files become part of the binary with zero runtime I/O.

Code Snippets

Embed static files in Go binary

package main

import (
	"embed"
	"html/template"
	"net/http"
)

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

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

// Embed templates
//go:embed templates/*.html
var templateFS embed.FS

func main() {
	// Serve embedded static files
	http.Handle("/static/",
		http.FileServer(http.FS(staticFiles)))

	// Parse embedded templates
	tmpl := template.Must(
		template.ParseFS(templateFS, "templates/*.html"))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tmpl.ExecuteTemplate(w, "index.html", nil)
	})
}

Revisions (0)

No revisions yet.