Gzip handler in Go
This is an example Go program which demonstrates writing a web page with gzipped contents.
package main import ( "compress/gzip" "io" "net/http" "strings" ) type gzipResponseWriter struct { io.Writer http.ResponseWriter } // Use the Writer part of gzipResponseWriter to write the output. func (w gzipResponseWriter) Write(b []byte) (int, error) { return w.Writer.Write(b) } func makeGzipHandler(fn http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Check if the client can accept the gzip encoding. if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { // The client cannot accept it, so return the output // uncompressed. fn(w, r) return } // Set the HTTP header indicating encoding. w.Header().Set("Content-Encoding", "gzip") gz := gzip.NewWriter(w) defer gz.Close() fn(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r) } } func handler(w http.ResponseWriter, r *http.Request) { // Send a simple message in text format. w.Header().Set("Content-Type", "text/plain") w.Write([]byte("This is a test.")) } func main() { http.ListenAndServe(":8081", makeGzipHandler(handler)) }
Web links
-
Roll your own gzip-encoded HTTP handler by Andrew Gerrand
My page is an adaptation of Andrew Gerrand's example using the modern Go syntax. Gerrand's example unfortunately no longer works.
-
go.httpgzip by daaku
Package httpgzip provides a http handler wrapper to transparently add gzip compression. This also contains a test script.
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer