Generated image
|| #resource #golang

Go: Embed Static Assets

Embedding static assets in a go binary for easy distribution

Problem

Go applications are compiled down to a single binary, and I love this. It is awesome for portability.

However, when building a more complex application, there are often times when the application needs other resources aside from code (e.g. images, HTML files, etc). The goal is to bundle them inside the binary file.

Solution

Go provides a standard way to accomplish this.

Folder structure

static/
    index.html
main.go

Golang code

package main

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

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

func main() {
	fsFolder, _ := fs.Sub(fs.FS(staticFiles), "static")
	fileServer := http.FileServer(http.FS(fsFolder))

	http.Handle("/static/", http.StripPrefix("/static/", fileServer))
	if err := http.ListenAndServe("0.0.0.0:8080", nil); err != nil {
		println(err)
	}
}

Where static/ is a folder with files to be embedded into the binary

Note that the comment above the staticFiles variable is essential to tell the compiler where to find the files to embed. The format is //go:embed <paths>.

Check the docs for more info on the embed package.

Related


Maybe try another one?

SSH Audit Validate your SSH server is using secure encryption
2022.12.20
Reusing Partials in Hugo Avoid code duplication by reusing Hugo partials
2022.08.09
Format Kotlin with Ktlint Automate away discussions about code style and focus on what really matters: shipping product to users
2020.09.01