Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang gin gonic web framework proxy route to another backend

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)

like image 314
alpha_cod Avatar asked Aug 16 '16 08:08

alpha_cod


People also ask

What is reverse proxy in Golang?

A reverse proxy is a server that sits in front of web servers and forwards client (e.g. web browser) requests to web servers. They give you control over the request from clients and responses from the servers and then we can use that to leverage benefits like caching, increased security and many more.

Is Gin gonic a framework?

Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to httprouter. If you need performance and good productivity, you will love Gin.

Does go need reverse proxy?

Always use reverse proxy. This way are not exposing application's framework to internet. Nginx being standard webserver gets security patches/fixes much more frequently to secure your APIs or Urls which you can upgrade without worrying about updating your GO application.

What is gin proxy used for?

Reverse proxies are great to handle logging, tracing, and authentication on applications you don't own or which you cannot modify the source code to make them do what you need.


2 Answers

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)
    }
}
like image 165
alpha_cod Avatar answered Oct 18 '22 15:10

alpha_cod


when you use director:

req.URL.Scheme = "http"
req.Host, req.URL.Host = "google.com", "google.com"
like image 37
kaynAw Avatar answered Oct 18 '22 15:10

kaynAw