如何解决如何在代理请求时在 Go Gin 中设置新的请求正文
我正在尝试代理 HTTP 调用,并尝试在将 JSON 正文发送到代理服务之前对其进行修改。但是,如果我尝试使用任何新数据修改 c.Request.Body,POST 请求将以 400 错误格式结束。但是,如果我再次将相同的先前正文数据设置为 c.Request.Body,那么代理调用就可以正常工作了。
Gin 函数
func Forward(c *gin.Context) {
remoteURL := c.Query("url")
remote,_ := url.Parse(remoteURL)
var bodyBytes []byte
if c.Request.Body != nil {
bodyBytes,_ = ioutil.ReadAll(c.Request.Body)
}
newBody := string(bodyBytes)
newBody = strings.Replace(newBody,"testString","testString1",-1)
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(newBody)))
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.Director = func(req *http.Request) {
req.Header = c.Request.Header
req.Host = remote.Host
req.URL.Scheme = remote.Scheme
req.URL.Host = remote.Host
req.URL.Path = remote.Path
}
proxy.ServeHTTP(c.Writer,c.Request)
}
卷曲命令:
curl --location --request POST 'http://localhost:8020/v1/proxy?url=https://entgkdbyzqm27.x.pipedream.net/' \
--header 'Content-Type: application/json' \
--data-raw '{
"id": "testString"
}'
如果我知道如何在 Gin 中正确设置请求正文,我将不胜感激。
解决方法
您可能遇到了 Content-Length
不匹配问题。更换后,新的身体比以前的身体长。
编写 Director
函数如下:
proxy.Director = func(req *http.Request) {
// clone the headers
req.Header = c.Request.Header.Clone()
// 1. set new header
req.Header.Set("Content-Length",strconv.Itoa(len(newBody)))
// 2. also update this field
req.ContentLength = int64(len(newBody))
// the rest stays the same
req.Host = remote.Host
req.URL.Scheme = remote.Scheme
req.URL.Host = remote.Host
req.URL.Path = remote.Path
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。