gin proxy代理

November 24, 2022

gin使用httputil.NewSingleHostReverseProxy实现proxy服务代理。

代码示例

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://www.iarno.cn")
	if err != nil {
		panic(err)
	}

	proxy := httputil.NewSingleHostReverseProxy(remote)

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

参考

https://le-gall.bzh/post/go/a-reverse-proxy-in-go-using-gin/

Goproxy代理

IARNO

服务端开发

Django 项目实践01