donglian1953
donglian1953
2014-04-15 14:19
浏览 415
已采纳

如何在Go中GZIP压缩http请求?

My application is rejecting this, but when I curl the data it is working, so it seems there is somewhere that I am confused with how to compress this http payload in Go.

    var buf bytes.Buffer
    g := gzip.NewWriter(&buf)
    g.Write([]byte("apples")
    req, err := http.NewRequest("POST", q.host, bytes.NewReader(buf.Bytes()))
    ...
    req.Header.Set("Content-Type", "text/plain")
    req.Header.Set("Content-Encoding", "gzip")
    resp, err := client.Do(req)

Does someone see where I am going wrong?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzhanglu4591
    douzhanglu4591 2014-04-15 14:49
    已采纳

    Looks like the main issue is that I needed to close the gzip Writer:

    b, err := batch.Json()
    ....
    var buf bytes.Buffer
    g := gzip.NewWriter(&buf)
    if _, err = g.Write(b); err != nil {
        slog.Error(err)
        return
    }
    if err = g.Close(); err != nil {
        slog.Error(err)
        return
    }
    req, err := http.NewRequest("POST", q.host, &buf)
    
    点赞 评论
  • dph23577
    dph23577 2014-04-16 19:16

    Another way to do this is to use the copy function

    func HttpHandler2(req *http.Request) {
        var b bytes.Buffer
        var buf bytes.Buffer
        g := gzip.NewWriter(&buf)
    
        _, err := io.Copy(g, &b)
        if err != nil {
            slog.Error(err)
            return
        }    
    }
    
    点赞 评论

相关推荐