package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http/httputil"
"net/url"
"strings"
)
// reverseProxy 方向代理
func reverseProxy(c *gin.Context) {
u, _ := url.Parse("http://127.0.0.1:11888") //要代理的地址
proxy := httputil.NewSingleHostReverseProxy(u)
c.Request.URL.Path = strings.TrimPrefix(c.Request.URL.Path, "/api") // 将/api/xx路由转为/xx路由
proxy.ServeHTTP(c.Writer, c.Request)
}
func main() {
r := gin.Default()
r.LoadHTMLGlob("./dist/*.html") // 添加入口index.html
r.Static("/favicon.ico", "./dist/favicon.ico")
r.Static("/static", "./dist/static") // 添加资源路径
r.StaticFile("/", "dist/index.html") //前端接口
api := r.Group("/api") // 以/api路由开头
api.POST("/*name", reverseProxy) // 代理POST接口
api.GET("/*name", reverseProxy) // 代理GET接口
fmt.Println("http://localhost:28180")
err := r.Run(":28180")
if err != nil {
panic("端口被占用")
}
}
使用Go反向代理
最新推荐文章于 2023-09-20 19:52:22 发布