Go代理中间件和修改响应

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

Go proxy middleware and modify response

问题

你可以使用httputil.ReverseProxyModifyResponse方法来接收和修改来自微服务的响应。这个方法接受一个func(*http.Response) error类型的函数作为参数,你可以在这个函数中对响应进行修改。

下面是一个示例代码:

proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ModifyResponse = func(resp *http.Response) error {
    // 在这里对响应进行修改
    resp.Header.Set("X-Custom-Header", "Modified")
    return nil
}

return func(c *gin.Context) {
    proxy.ServeHTTP(c.Writer, c.Request)
}

ModifyResponse函数中,你可以通过resp参数来访问和修改响应的各个属性,比如头部信息、状态码、响应体等。在示例中,我通过resp.Header.Set方法添加了一个自定义的头部信息。

你可以根据需要在ModifyResponse函数中进行其他的修改操作。

英文:

I'm trying to proxy a request from a Go backend to a microservice and modify the response before it is sent to the client. The request chain is: Client -> Go backend -> microservice -> Go backend -> client

I'm using the Go Gin framework. The working middleware:

func ReverseProxy(target string) gin.HandlerFunc {
	log.Println(target)
	url, err := url.Parse(target)
	if err != nil {
		log.Fatal(err)
	}
	proxy := httputil.NewSingleHostReverseProxy(url)
	return func(c *gin.Context) {
		proxy.ServeHTTP(c.Writer, c.Request)
	}
}

Now my question is: How can I receive and modify the response sent by the microservice?

答案1

得分: 4

使用ReverseProxyModifyResponse如何?例如,这将向响应中添加自定义标头。

func addCustomHeader(r *http.Response) error {
    r.Header["Hello"] = []string{"World"}
    return nil
}

proxy.ModifyResponse = addCustomHeader

ReverseProxy的详细信息请参考官方文档。

英文:

How about using ReverseProxy.ModifyResponse?

For example, this will add a custom header to the response.

func addCustomHeader(r *http.Response) error {
	r.Header["Hello"] = []string{"World"}
	return nil
}

proxy.ModifyResponse = addCustomHeader

huangapple
  • 本文由 发表于 2017年3月26日 02:11:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/43020079.html
匿名

发表评论

匿名网友

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

确定