Serving gzipped content for Go

后端 未结 4 2065
死守一世寂寞
死守一世寂寞 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:24

    There is yet another "out of the box" middleware now, supporting net/http and Gin:

    https://github.com/nanmu42/gzip

    net/http example:

    import github.com/nanmu42/gzip
    
    func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            writeString(w, fmt.Sprintf("This content is compressed: l%sng!", strings.Repeat("o", 1000)))
        })
    
        // wrap http.Handler using default settings
        log.Println(http.ListenAndServe(fmt.Sprintf(":%d", 3001), gzip.DefaultHandler().WrapHandler(mux)))
    }
    
    func writeString(w http.ResponseWriter, payload string) {
        w.Header().Set("Content-Type", "text/plain; charset=utf8")
        _, _ = io.WriteString(w, payload+"\n")
    }
    

    Gin example:

    import github.com/nanmu42/gzip
    
    func main() {
        g := gin.Default()
    
        // use default settings
        g.Use(gzip.DefaultHandler().Gin)
    
        g.GET("/", func(c *gin.Context) {
            c.JSON(http.StatusOK, map[string]interface{}{
                "code": 0,
                "msg":  "hello",
                "data": fmt.Sprintf("l%sng!", strings.Repeat("o", 1000)),
            })
        })
    
        log.Println(g.Run(fmt.Sprintf(":%d", 3000)))
    }
    

提交回复
热议问题