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

(download)

Web links


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer