请教一个问题
使用 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
的错误
后来自己解决了,因为其他代码用到了ParseForm ,导致了ioutil.Readall清空了body ,所以用以下方式解决了
// 把request的内容读取出来
183
+ var bodyBytes []byte
184
+ if c.Request.Body != nil {
185
+ bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
186
+ }
187
+ // 把刚刚读出来的再写进去
188
+ c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
189
+ vs, _ := url.ParseQuery(string(bodyBytes))
190
+ tokenString = vs.Get("usertoken")
#2