Golang gin gonic web framework proxy route to another backend

风格不统一 提交于 2019-12-08 02:41:30

问题


How to reverse proxy web requests for a few routes to another backend in Gin Gonic web golang framework

Is there a way to directly forward in the Handle function as shown below?

router := gin.New() router.Handle("POST", "/api/v1/endpoint1", ForwardToAnotherBackend)


回答1:


You can do this with the standard library httputil.ReverseProxy.

I haven't found a reason to use gin myself yet, I'm a fan of sticking to stdlib whenever possible. However I believe you can wrap this ReverseProxy handler in gin.WrapH() to be able to use it with your gin router.




回答2:


This was the solution I used for reverse-proxying a specific subset of endpoints from gin framework to another backend:

router.POST("/api/v1/endpoint1", ReverseProxy()

func ReverseProxy() gin.HandlerFunc {

    target := "localhost:3000"

    return func(c *gin.Context) {
        director := func(req *http.Request) {
            r := c.Request
            req = r
            req.URL.Scheme = "http"
            req.URL.Host = target
            req.Header["my-header"] = []string{r.Header.Get("my-header")}
            // Golang camelcases headers
            delete(req.Header, "My-Header")
        }
        proxy := &httputil.ReverseProxy{Director: director}
        proxy.ServeHTTP(c.Writer, c.Request)
    }
}


来源:https://stackoverflow.com/questions/38970561/golang-gin-gonic-web-framework-proxy-route-to-another-backend

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!