net/http: http: ContentLength=222 with Body length 0

后端 未结 3 990
忘了有多久
忘了有多久 2021-02-05 12:37

I\'m trying to retry a request if there is a connection/proxy error. For some reasons I keep getting this error which doesn\'t seem to recover regardless the attepts to retry th

3条回答
  •  無奈伤痛
    2021-02-05 12:55

    Let's see what does http.NewRequest do

    rc, ok := body.(io.ReadCloser)
    if !ok && body != nil {
        rc = ioutil.NopCloser(body)
    }
    // The host's colon:port should be normalized. See Issue 14836.
    u.Host = removeEmptyPort(u.Host)
    req := &Request{
        Method:     method,
        URL:        u,
        Proto:      "HTTP/1.1",
        ProtoMajor: 1,
        ProtoMinor: 1,
        Header:     make(Header),
        Body:       rc,
        Host:       u.Host,
    }
    

    body is type of io.Reader, and convert to io.ReaderCloser by ioutil.NopCloser. As @Cerise Limón said, the Request.Body had been read and the stream is closer, so when you Do() again, the Body Length is 0.

    So, we could reset the Request.Body before invoke Do.

    func Post(URL string, form url.Values, cl *http.Client) ([]byte, error) {
        requestBodyString := form.Encode()
        req, err := http.NewRequest("POST", URL, strings.NewReader(requestBodyString))
        // ...
    
        rsp, err := do(cl, req, requestBodyString)
    
        //...
        return b, nil
    }
    
    func do(cl *http.Client, req *http.Request, requestBodyString string)(*http.Response, error){
        rsp, err := cl.Do(req)
        for i := 0; IsErrProxy(err); i++ {
            log.Errorf("Proxy is slow or down ")
            time.Sleep(6 * time.Second)
            // reset Request.Body
            req.Body = ioutil.NopCloser(strings.NewReader(requestBodyString))
            rsp, err = cl.Do(&req)
            if err == nil{
                return rsp, nil
            }
            if i > 10 {
    
                return nil, fmt.Errorf("after %v tries error: %v", i, err)
            }
        }
        return rsp, err
    }
    

提交回复
热议问题