Deploy and serve assets from a zip archive
When going through the sourcecode of the godoc.org service I came upon this gem called the zipfs
package. From the docs:
Package zipfs file provides an implementation of the FileSystem interface based on the contents of a .zip file.
Combine this with the FileServer handler from the net/http
package and you'll be able to serve your assets from a single zip archive.
I wouldn't recommend this strategy in production but it beats embedding your HTML templates, CSS files and your API docs in your Go code.
The following is an example of a HTTP service which serves the contents of the given archive from the /assets/
path:
package main
import (
"archive/zip"
"flag"
"log"
"net/http"
"golang.org/x/tools/godoc/vfs/httpfs"
"golang.org/x/tools/godoc/vfs/zipfs"
)
func main() {
zipPath := flag.String("zip", "assets.zip", "zip file containing assets")
httpAddr := flag.String("http", "localhost:6011", "http address")
flag.Parse()
r, err := zip.OpenReader(*zipPath)
if err != nil {
log.Fatal(err)
}
fs := zipfs.New(r, *zipPath)
m := http.NewServeMux()
m.Handle("/assets/", http.FileServer(httpfs.New(fs)))
log.Print("Listening on ", *httpAddr)
if err := http.ListenAndServe(*httpAddr, m); err != nil {
log.Fatal("ListenAndServe:", err)
}
}