golang代理中的传输编码分块

c3frrgcw  于 2022-12-31  发布在  Go
关注(0)|答案(1)|浏览(137)

我是golang的新手,我正在尝试建立一个小型的本地代理,请求可以从Postman -〉localhost:9097 -〉localhost:9098来回运行,但是内容长度是120,响应正文是一堆乱七八糟的东西:
x1c 0d1x我希望得到一个类似于 {“result”:{“编号”:“1”,“价格”:100个,【数量】:1 } }
如果一个请求直接发送到:9098我看到响应头transfer-encingchunked.你知道如何调整我的代码来正确解析来自服务器的响应正文并将其发送回客户端吗?

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))
}
30byixjq

30byixjq1#

现在设法解决了这个问题!感谢Steffen Ullrich指出这个问题可能是“关于压缩内容”。删除作为mentioned here的Accept-Encoding报头工作起来很有魅力。

...
// 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
...

相关问题