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)
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.
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.
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.
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.
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)
}
}
when you use director:
req.URL.Scheme = "http"
req.Host, req.URL.Host = "google.com", "google.com"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With