golang httputil.NewSingleHostReverseProxy 反向代理使用问题

请教大家一个问题

使用 httputil.NewSingleHostReverseProxy 反向代理一个spring boot 的 服务。

func NewGinProxy(upstream string, prefix string) (*ProxyRouter, error) {
    target, err := url.Parse(upstream)
    if err != nil {
        return nil, err
    }
    targetQuery := target.RawQuery

    director := func(req *http.Request) {

        req.Host = target.Host // -- 加入这句 --

        req.URL.Scheme = target.Scheme

        req.URL.Host = target.Host

        req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path[len(prefix):len(req.URL.Path)])

        if targetQuery == "" || req.URL.RawQuery == "" {

            req.URL.RawQuery = targetQuery + req.URL.RawQuery

        } else {

            req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery

        }

        //if _, ok := req.Header["User-Agent"]; !ok {

        // explicitly disable User-Agent so it's not set to default value

        //req.Header.Set("User-Agent", "")

        //}
        req.Header.Set("HTTP_X_FORWARDED_FOR", req.RemoteAddr)

    }

    transport := &http.Transport{
        Proxy: http.ProxyFromEnvironment,
        DialContext: (&net.Dialer{
            Timeout:   30 * time.Second,
            KeepAlive: 30 * time.Second,
            DualStack: true,
        }).DialContext,
        ForceAttemptHTTP2:     false,
        MaxIdleConns:          100,
        IdleConnTimeout:       90 * time.Second,
        TLSHandshakeTimeout:   10 * time.Second,
        ExpectContinueTimeout: 100 * time.Second,
    }

    return &ProxyRouter{
        proxy: &httputil.ReverseProxy{Director: director, Transport: transport},
    }, nil
}
//反向代理网关
func (p *ProxyRouter) Handler(c *gin.Context) {

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

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

    port := "30041"

    biz_url := "http://127.0.0.1:30021/"
    biz_path := "/biz"
    fmt.Println("端口:", port)

    //业务服务反向代理目标
    g, _ := NewGinProxy(biz_url, biz_path)
    router.Any("/biz/*all", g.Handler)


    router.Run(":" + port)
}

Content-Type: application/x-www-form-urlencoded

在spring boot 端使用 request.getParameter ,就会出现 类似

http: proxy error: http: ContentLength=2886 with Body length 0

的错误,尝试了很多方法都无法解决

讨论数量: 2

1、没法复现 最好抓个包

2、按照源码逻辑你好像设置了httputil.ReverseProxy.ModifyResponse 返回了什么错误。

2周前 评论

@1112 后来自己解决了,因为其他地方用到了 c.FormValue ,里面用到了 ParseForm导致的 :joy:

2周前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!