How to set reverse proxy in Go with Gin


This post is written 22 months ago. Probably the information might be out of date.

How to implement a reverse proxy

httputil has a method ‘NewSingleHostReverseProxy’ which returns a struct ‘ReverseProxy’. The ReverseProxy struct contains a Director field.

A director is a function where you tell the reverse proxy what to do with the incoming request.

In this sample code, I used itunes api.

main.go
func proxy(ctx *gin.Context) {
	// declare a remote url for reverse proxy
	remote, err := url.Parse("https://itunes.apple.com/search")
	if err != nil {
		panic(err)
	}

	// declare reverse ReverseProxy struct
	proxy := httputil.NewSingleHostReverseProxy(remote)
	// modify host, header with Director
	proxy.Director = func(req *http.Request) {
		req.Header = ctx.Request.Header
		req.Host = remote.Host
		req.URL.Scheme = remote.Scheme
		req.URL.Host = remote.Host
		req.URL.Path = ctx.Param("endpoint")
	}

	proxy.ServeHTTP(ctx.Writer, ctx.Request)
}
copied!
main.go
func main() {
	g := gin.Default()
	g.Any("/proxy/*endpoint", proxy)
	g.Run(":8000")
}
copied!

In this example code, I coded all program above in main.go file. When I run these command below, I can start the program and get response correctly

go run main.go
curl "localhost:9000/proxy/search?term=chrvches&country=jp&artribute=artistName&limit=1"
copied!
buy me a coffee