Lars Wiegman

  • Home
  • Skills
  • Contact
  • Blog

Deploy and serve assets from a zip archive

posted on August 4, 2015 #

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)
    }
}

Read Next:

Shell history expansion

Shells like Bash and Zsh support all kinds of expansions. One I use on a daily basis is the history expansion which expands to the last word of previous command in history. The next example would open my editor with ‘new.txt’ file. % cp old.txt new.txt % vim !$ Continue »

  • Home
  • Skills
  • Blog
  • Contact
  • •
  • Archive
  • Feed
  • GitHub

Copyright © 2007-2024 Lars Wiegman