func forwarderHandlerFunc(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
u, _ := url.Parse(r.RequestURI)
req, _ := http.NewRequest(r.Method, fmt.Sprintf("%s%s", apiUrl, u.Path), r.Body)
fmt.Printf(fmt.Sprintf("%s\n", nutils.ReaderToString(req.Body)))
resp, _ := client.Do(req)
resp.Write(w)
}
我正在尝试将传入的 HTTP 请求转发到另一个端点,同时将正文(包括 POST/PUT 表单数据)复制到新请求中。
但是,它似乎不起作用,即使 Body 似乎打印出正确的数据。
打印输出为:
email=meh%!g(MISSING)mail.com
我该如何解决?
编辑:添加了更多调试信息,这次打印出 resp 的输出
func forwarderHandlerFunc(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
u, _ := url.Parse(r.RequestURI)
req, _ := http.NewRequest(r.Method, fmt.Sprintf("%s%s", apiUrl, u.Path), r.Body)
fmt.Printf(fmt.Sprintf("%s\n", nutils.ReaderToString(req.Body)))
resp, _ := client.Do(req)
b,_ := ioutil.ReadAll(resp.Body)
fmt.Printf(fmt.Sprintf("%s\n", nutils.BytesToString(b)))
resp.Write(w)
}
$ go install && gom-proxy-forwarder run --listen localhost:5002 --api-url http://localhost:5001 email=meh2%!g(MISSING)mail.com { "email": null }
它不应该为空。应该是 meh@gmail.com
最佳答案
明白了。问题是我在 Python 的 Flask 服务器中的端点不支持 Go 的 Request 坚持的分块编码。
当我像 req.ContentLength = 25
那样手动指定 ContentLength 时,它起作用了。
经验教训:问题可能并不总是出在您的 Go 代码上。
关于go - 为什么我的 GoLang POST 请求没有填充数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339877/