如何在Transport.RoundTrip中保持http.Request.Body不关闭?

时间:2018-02-01 13:09:51

标签: http go proxy request

我构建代理,当代理到127.0.0.1:9902失败时,代理到127.0.0.1:9903。

但是,当代理到127.0.0.1:9902失败时,http请求正文将在Transport.RoundTrip中关闭,因此127.0.0.1:9903的代理将是错误的(关闭正文的读取无效)。

我已经被困扰了很长时间。任何一位大师都可以帮助我,并提出一个想法代理功能吗?非常感谢你!

func proxy(w http.ResponseWriter, r *http.Request) {
    ok := proxyTO("http://127.0.0.1:9902", w, r)  //server127.0.0.1:9902 not open,so r.Body close after proxyTo
    if ok == false {
        proxy1("http://127.0.0.1:9903", w, r)   //error http: invalid Read on closed Body
    }
}

//any idea on proxyTo function?
func proxyTo(addr string, w http.ResponseWriter, r *http.Request) bool {
    urlLs, _ := url.Parse(addr)
    r.URL.Host = urlLs.Host
    r.URL.Scheme = urlLs.Scheme
    r.Host = urlLs.Host
    r.RequestURI = ""

    resp, err := http.DefaultTransport.RoundTrip(r)    //how to keep r.Body not close when error
    if err != nil {
        return false
    }
    if resp.StatusCode != http.StatusOK {
        w.WriteHeader(resp.StatusCode)
        return true              //here return is ok? 
    }
    for name, vals := range resp.Header {
        for _, val := range vals {
            w.Header().Add(name, val)
        }
    }
    io.Copy(w, resp.Body)

    resp.Body.Close()
    return true
}

0 个答案:

没有答案