11

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)

blackgreen
  • 34,072
  • 23
  • 111
  • 129
alpha_cod
  • 1,933
  • 5
  • 25
  • 43

3 Answers3

12

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())

and:

func ReverseProxy() gin.HandlerFunc {

    target := "localhost:3000"

    return func(c *gin.Context) {
        director := func(req *http.Request) {
            r := c.Request

            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)
    }
}
blackgreen
  • 34,072
  • 23
  • 111
  • 129
alpha_cod
  • 1,933
  • 5
  • 25
  • 43
3

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.

baloo
  • 7,635
  • 4
  • 27
  • 35
  • Thanks for the help. Could you give me an example of how to do this? – alpha_cod Aug 17 '16 at 10:51
  • @alpha_cod See the link above and then click Example on that page. You simply have to adapt that to the gin framework if you really need to use their router. – baloo Aug 17 '16 at 10:55
1

when you use director:

req.URL.Scheme = "http"
req.Host, req.URL.Host = "google.com", "google.com"
kaynAw
  • 11
  • 1