gzip压缩到http responseWriter [英] gzip compression to http responseWriter

查看:89
本文介绍了gzip压缩到http responseWriter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Go的新手.但是我正在玩REST Api.我无法从json.Marshal中获得与json.Encoder在我拥有的两个函数中相同的行为

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

我想使用此功能gzip我的回复:

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

这是go函数:

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

}

但是当我取消评论时:

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

它工作正常.

推荐答案

您需要先刷新或关闭gzip编写器,然后才能访问基础字节,例如

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

否则,不会收集gzip编写器中已缓冲但尚未写到最终流中的内容.

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

这篇关于gzip压缩到http responseWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆