英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论