在Golang代理中使用的Transfer-Encoding: chunked。

huangapple go评论86阅读模式
英文:

Transfer-encoding chunked in golang proxy

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是golang的新手,正在尝试构建一个小型的本地代理。请求从Postman -> localhost:9097 -> localhost:9098 和返回都基本正常。但是响应的内容长度是120,而响应体却是一些无意义的字符。

我期望得到的是一个json格式的响应体,类似于 { "result": { "id": "1", "price": 100, "quantity": 1 } }

如果我直接请求 :9098,我发现响应头中的 transfer-encodingchunked。你有什么办法可以调整我的代码,以正确解析服务器的响应体并将其发送回客户端吗?

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))
}
英文:

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:
在Golang代理中使用的Transfer-Encoding: chunked。
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))
}

答案1

得分: 1

成功解决了!感谢Steffen Ullrich指出问题可能是“关于压缩内容”的。按照这里提到的方法,删除Accept-Encoding头部字段就可以解决问题了。

...
// 如果你手动设置了Accept-Encoding请求头部字段,那么压缩的响应将不会自动解压缩
req.Header.Del("Accept-Encoding")

freq.Header = req.Header
...
英文:

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

huangapple
  • 本文由 发表于 2022年12月29日 16:13:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/74948691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定