Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to GZIP Compress an http request in Go?

Tags:

gzip

go

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?

like image 943
Kyle Brandt Avatar asked Apr 15 '14 14:04

Kyle Brandt


People also ask

How do I compress a HTTP request body?

To compress the HTTP request body, you must attach the HTTP header indicating the sending of HTTP request body compressed in gzip format while sending the request message from the Web Service client. Implement the processing for attaching the HTTP header in the client application.

How do I use gzip in Golang?

Copy all read bytes into the new file and close the fileNewWriter() from the compress/gzip package, we create a new gzip writer. Then we can use Write to write the compressed bytes in the file. After finishing, we need to close the file.

How do I compress a file in Golang?

To compress a File in Golang, we use the gzip command. Then create a path to trace our file. Then leave the command to read our file.


1 Answers

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)
like image 119
Kyle Brandt Avatar answered Oct 06 '22 01:10

Kyle Brandt