Packr is a simple solution for bundling static assets inside of Go binaries.
Installation
go get -u github.com/gobuffalo/packr
Usage
// set up a new box by giving it a (relative) path to a folder on disk: box := packr.NewBox("./templates") // Get the string representation of a file, or an error if it doesn't exist: html, err := box.FindString("index.html") // Get the []byte representation of a file, or an error if it doesn't exist: html, err := box.FindBytes("index.html")
A box represents a folder, and any sub-folders, on disk that you want to have access to in your binary. When compiling a binary using the packr
CLI the contents of the folder will be converted into Go files that can be compiled inside of a „standard“ go binary. Inside of the compiled binary the files will be read from memory. When working locally the files will be read directly off of disk.
Usage with HTTP
package main import ( "net/http" "github.com/gobuffalo/packr" ) func main() { box := packr.NewBox("./templates") http.Handle("/", http.FileServer(box)) http.ListenAndServe(":3000", nil) }
Building a Binary
packr go build