doubiaozhan0745 2016-08-24 01:06
浏览 68
已采纳

gzip压缩到http responseWriter

I'm new to Go. But am playing with a REST Api. I cant get the same behavior out of json.Marshal as json.Encoder in two functions i have

I wanted to use this function to gzip my responses:

func gzipFast(a *[]byte) []byte {
    var b bytes.Buffer
    gz := gzip.NewWriter(&b)
    defer gz.Close()
    if _, err := gz.Write(*a); err != nil {
        panic(err)
    }
    return b.Bytes()
}

But this function returns this:

curl http://localhost:8081/compressedget --compressed --verbose
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8081 (#0)
> GET /compressedget HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/7.47.0
> Accept: */*
> Accept-Encoding: deflate, gzip
> 
< HTTP/1.1 200 OK
< Content-Encoding: gzip
< Content-Type: application/json
< Date: Wed, 24 Aug 2016 00:59:38 GMT
< Content-Length: 30
< 
* Connection #0 to host localhost left intact

Here is the go function:

func CompressedGet(w http.ResponseWriter, r *http.Request, ps  httprouter.Params) {

    box := Box{Width: 10, Height: 20, Color: "gree", Open: false}
    box.ars = make([]int, 100)
    for i := range box.ars {
        box.ars[i] = i
    }
    //fmt.Println(r.Header.Get("Content-Encoding"))

    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Content-Encoding", "gzip")
    b, _ := json.Marshal(box)
    //fmt.Println(len(b))
    //fmt.Println(len(gzipFast(&b)))

    fmt.Fprint(w, gzipFast(&b))
    //fmt.Println(len(gzipSlow(b)))
    //gz := gzip.NewWriter(w)
    //defer gz.Close()
    //json.NewEncoder(gz).Encode(box)
    r.Body.Close()

}

But when i uncomment:

//gz := gzip.NewWriter(w)
//defer gz.Close()
//json.NewEncoder(gz).Encode(box)

it works fine.

  • 写回答

3条回答 默认 最新

  • doumaqing6652 2016-08-24 13:58
    关注

    You need to flush or close your gzip writer before accessing the underlying bytes, e.g.

    func gzipFast(a *[]byte) []byte {
        var b bytes.Buffer
        gz := gzip.NewWriter(&b)
        if _, err := gz.Write(*a); err != nil {
            gz.Close()
            panic(err)
        }
        gz.Close()
        return b.Bytes()
    }
    

    Otherwise what's been buffer in the gzip writer, but not yet written out to the final stream isn't getting collected up.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?