How to GZIP Compress an http request in Go?

huangapple go评论81阅读模式
英文:

How to GZIP Compress an http request in Go?

问题

我的应用程序拒绝了这个请求,但是当我使用curl发送数据时,它是有效的,所以似乎我在如何在Go中压缩这个HTTP负载方面有些困惑。

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)

有人看到我错在哪里吗?

英文:

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?

答案1

得分: 9

看起来主要问题是我需要关闭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)
英文:

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)

答案2

得分: 4

另一种方法是使用copy函数:

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

请注意,我已经将代码中的&替换为了&,以便正确显示代码。

英文:

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

huangapple
  • 本文由 发表于 2014年4月15日 22:19:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/23086488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定