如何解决在 httputil 反向代理中设置请求正文
我正在做一个反向代理的事情,它只是将您的请求转发到另一台服务器上,但我无法设置正文。
// post request from endpoint /forwarder.
// Called this using Router.post('/forwarder',ReverseProxy())
func ReverseProxy() gin.HandlerFunc {
endpoint := "http://localhost:3001"
remote,_ := url.Parse(endpoint)
proxy := httputil.NewSingleHostReverseProxy(remote)
return func(c *gin.Context) {
body,_ := ioutil.ReadAll(c.Request.Body)
body_string := string(body)
fmt.Printf("this is data from rqeuest\n%v\n",c.Request.Body)
//Define the director func
proxy.Director = func(req *http.Request) {
req.Header = c.Request.Header
req.Body = ioutil.NopCloser(strings.NewReader(body_string))
req.ContentLength = int64(len(body_string))
fmt.Printf("this is data different \n%v\n",req.Body)
temp,_ := ioutil.ReadAll(req.Body)
fmt.Printf("this is data from req.body\n%v\n",string(temp))
req.Host = remote.Host
req.URL.Scheme = remote.Scheme
req.URL.Host = remote.Host
req.URL.Path = c.Param("proxyPath")
}
proxy.ServeHTTP(c.Writer,c.Request)
}
}
结果是
http: proxy error: http: ContentLength=43 with Body length 0
删除 req.ContentLength = int64(len(body_string))
会将请求转发到在 localhost:3001
上运行的服务器,但正文为 undefined
。
如何设置主体?
解决方法
你不应该设置正文,你必须写信给它。喜欢:
io.Copy(req.Body,c.Request.Body)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。