Question

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?

Was it helpful?

Solution

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)

OTHER TIPS

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
    }    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top