Serving gzipped content for Go

后端 未结 4 2003
死守一世寂寞
死守一世寂寞 2021-01-30 17:00

I\'m starting to write server-side applications in Go. I\'d like to use the Accept-Encoding request header to determine whether to compress the response entity usi

4条回答
  •  生来不讨喜
    2021-01-30 17:13

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

提交回复
热议问题