1

I'm new to golang and I'm trying to build a small local proxy. The request kinda works from Postman -> localhost:9097 -> localhost:9098 and back. But the content-length is 120 and the response body is just gibberish:
enter image description here I expect to get a json body like { "result": { "id": "1", "price": 100, "quantity": 1 } }

If a make a request directly to :9098 I see that the response header transfer-encoding is chunked. Any idea how to adjust my code to parse the response body from the server properly and send it back to the client?

func httpHandler(w http.ResponseWriter, req *http.Request) {
    reqURL := fmt.Sprint(req.URL)
    newUrl = "http://localhost:9098" + reqURL

    //forward request
    client := http.Client{}
    freq, reqerror := http.NewRequest(req.Method, newUrl, nil)
    if reqerror != nil {
        log.Fatalln(reqerror)
    }
    freq.Header = req.Header
    freq.Body = req.Body

    resp, resperr := client.Do(freq)
    if resperr != nil {
        log.Println(resperr)
        fmt.Fprintf(w, "Error. No response")
        return
    }

    defer resp.Body.Close()

    body, ioerr := io.ReadAll(resp.Body)
    if ioerr != nil {
        log.Println(ioerr)
        fmt.Fprintf(w, "IO Error (Response body)")
        return
    }

    w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
    w.WriteHeader(resp.StatusCode)

    fmt.Fprintf(w, string(body))
}
mroizo
  • 81
  • 5
  • *" the response body is just gibberish!"* - please be more detailed what this means, i.e. what kind of body you expect and what you get instead. Handling of chunked transfer encoding should be done transparently in net/http so you might be looking at the wrong cause of your problem. Maybe it is about compressed content instead? – Steffen Ullrich Dec 29 '22 at 08:39
  • I've updated my post with screenshot of "gibberish" and what I actually expect to be the response body. – mroizo Dec 29 '22 at 09:16
  • What is your client which outputs this "gibberish"? Please don't provide a screenshot of it but provides the actual bytes (encoded as hex or base64 or as binary for download) so that the real information are preserved and also can be processed by others (contrary to just a screenshot). – Steffen Ullrich Dec 29 '22 at 09:57

1 Answers1

1

Managed to solve this now! Thanks to Steffen Ullrich for pointing out the the issue could be "about compressed content". Removing the Accept-Encoding header as mentioned here worked like a charm.

...
// if you manually set the Accept-Encoding request header, than gzipped response will not automatically decompressed
req.Header.Del("Accept-Encoding")

freq.Header = req.Header
...
mroizo
  • 81
  • 5