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 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧