How to set new request body in Go Gin while proxing a request

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

How to set new request body in Go Gin while proxing a request

问题

我正在尝试代理一个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.ServeHTTP(c.Writer, c.Request)
}

你可以使用上述代码将请求体中的字符串"testString"替换为"testString1"。这样设置后,再进行代理调用时就会使用修改后的请求体。

希望对你有所帮助!

英文:

I'm trying to proxy an HTTP call, and trying to modify the JSON body before sending it to the proxy service. However, if I try to modify the c.Request.Body with any new data, the POST request ends in 400 bad format. But if I set the same previous body data again to c.Request.Body then the proxy call works without a problem.

Gin Function

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 Command:

curl --location --request POST 'http://localhost:8020/v1/proxy?url=https://entgkdbyzqm27.x.pipedream.net/' \
--header 'Content-Type: application/json' \
--data-raw '{
    "id": "testString"
}'

I would be much obliged if I could know how to set the request body correctly in Gin.

答案1

得分: 5

你可能遇到了Content-Length不匹配的问题。在替换后,新的请求体长度比之前的长。

请按照以下方式编写Director函数:

    proxy.Director = func(req *http.Request) {
        // 克隆请求头
        req.Header = c.Request.Header.Clone()

        // 1. 设置新的请求头
		req.Header.Set("Content-Length", strconv.Itoa(len(newBody)))

        // 2. 同时更新该字段
		req.ContentLength = int64(len(newBody))

        // 其余部分保持不变
        req.Host = remote.Host
        req.URL.Scheme = remote.Scheme
        req.URL.Host = remote.Host
        req.URL.Path = remote.Path
    }
英文:

You're probably having a Content-Length mismatch. After the replace, the new body is longer than the previous one.

Write the Director function as follows:

    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
    }

huangapple
  • 本文由 发表于 2021年6月30日 22:24:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/68196655.html
匿名

发表评论

匿名网友

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

确定