我正在尝试代理 HTTP 调用,并尝试在将 JSON 正文发送到代理服务之前对其进行修改。但是,如果我尝试使用任何新数据修改c.Request.Body,则POST请求以400错误格式结束。但是,如果我再次将相同的先前正文数据设置为 c.Request.Body,则代理调用可以正常工作。杜松子酒功能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中正确设置请求正文,我将非常有义务。
1 回答
慕工程0101907
TA贡献1887条经验 获得超5个赞
您可能有不匹配的情况。替换后,新主体比前一个主体长。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
}
添加回答
举报
0/150
提交
取消