使用httputil中ReverseProxy反向代理遇到的坑

坑描述,当POST ContentType=="application/x-www-form-urlencoded"时,反向代理报错:http: proxy error: http: ContentLength=xx with Body length 0

即进行反向代理时,body为空,报错代码:

res, err := transport.RoundTrip(outreq)
if err != nil {
    p.logf("http: proxy error: %v", err)
    rw.WriteHeader(http.StatusInternalServerError)
    return
}

出错后直接返回了HTTP 500,没有进行后向代理。
ServeHTTP的代码如下:

func (this *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	remote, err := url.Parse("http://" + this.host + ":" + this.port)
	if err != nil {
		panic(err)
	}
	proxy := NewSingleHostReverseProxy(remote)
	proxy.ServeHTTP(w, r)
}

在ServeHTTP中并没有做其他多余操作,只是调用了r.ParseForm()进行Form解析,坑就在这里。
由于r.Body是一个接口io.ReadCloser,ParseForm中对reader进行了ioutil.ReadAll(reader),而ioutil.ReadAll中对Buffer进行了清空重用。
去掉r.ParseForm()就可以了。

posted on 2017-12-21 10:16  angry-baby  阅读(3187)  评论(0编辑  收藏  举报

导航