使用  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
的错误