Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Golang gonic gin behind proxy subpath; reverse proxy

14 Sep 2022 »

Sub-groups of routes #1205

https://github.com/gin-gonic/gin/issues/1205

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()

    v1 := r.Group("/api/v1")
    {
        auth := v1.Group("/auth")
        {
            auth.GET("/", func(c *gin.Context) {
                c.JSON(200, gin.H{
                    "v1-auth": true,
                })
            })
        }

    }
    r.Run() // listen and serve on 0.0.0.0:8080
}

Proxy route to another backend #686

https://github.com/gin-gonic/gin/issues/686

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

A simple reverse proxy in Go using Gin

package main

import (
	"net/http"
	"net/http/httputil"
	"net/url"

	"github.com/gin-gonic/gin"
)

func proxy(c *gin.Context) {
	remote, err := url.Parse("http://myremotedomain.com")
	if err != nil {
		panic(err)
	}

	proxy := httputil.NewSingleHostReverseProxy(remote)
	//Define the director func
	//This is a good place to log, for example
	proxy.Director = func(req *http.Request) {
		req.Header = c.Request.Header
		req.Host = remote.Host
		req.URL.Scheme = remote.Scheme
		req.URL.Host = remote.Host
		req.URL.Path = c.Param("proxyPath")
	}

	proxy.ServeHTTP(c.Writer, c.Request)
}

func main() {

	r := gin.Default()

	//Create a catchall route
	r.Any("/*proxyPath", proxy)

	r.Run(":8080")
}