2016-08-16 08:56
浏览 31

Golang杜松子酒Gonic Web框架代理路由到另一个后端

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)

图片转代码服务由CSDN问答提供 功能建议

如何在 Gin Gonic 网络golang框架

是否可以直接在Handle函数中转发,如下所示 ?

router:= gin.New() router.Handle(“ POST”,“ / api / v1 / endpoint1,ForwardToAnotherBackend)

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutangdan3588 2016-08-16 12:27

    You can do this with the standard library httputil.ReverseProxy.

    I haven't found a reason to use gin myself yet, I'm a fan of sticking to stdlib whenever possible. However I believe you can wrap this ReverseProxy handler in gin.WrapH() to be able to use it with your gin router.

    打赏 评论
  • dongwu9647 2016-08-18 04:23

    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()
    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)
    打赏 评论

相关推荐 更多相似问题