Serving gzipped content for Go

For the sake of completeness, I eventually answered my own question with a handler that is simple and specialises in solving this issue.

  • https://pkg.go.dev/github.com/rickb777/servefiles?tab=doc
  • https://github.com/rickb777/servefiles

This serves static files from a Go http server, including the asked-for performance-enhancing features. It is based on the standard net/http ServeFiles, with gzip/brotli and cache performance enhancements.


The New York Times have released their gzip middleware package for Go.

You just pass your http.HandlerFunc through their GzipHandler and you're done. It looks like this:

package main

import (
    "io"
    "net/http"
    "github.com/nytimes/gziphandler"
)

func main() {
    withoutGz := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/plain")
        io.WriteString(w, "Hello, World")
    })

    withGz := gziphandler.GzipHandler(withoutGz)

    http.Handle("/", withGz)
    http.ListenAndServe("0.0.0.0:8000", nil)
}

There is no “out of the box” support for gzip-compressed HTTP responses yet. But adding it is pretty trivial. Have a look at

https://gist.github.com/the42/1956518

also

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/cgUp8_ATNtc

Tags:

Http

Webserver

Go