timakin/bodyclose

False positive with a retry for

mostafah opened this issue · 0 comments

The following code is fine, because it closes the body only when the error is nil, but gets response body must be closed errors on both the d.client.Do(req) lines.

func (d *Dispatcher) call(req *http.Request) {
	// keep retrying the request until the error is nil
	tries := 0
	wait := time.Second
	resp, err := d.client.Do(req)
	for err != nil && tries < d.retries {
		// wait a while
		time.Sleep(wait)
		wait *= 2
		// try again
		resp, err = d.client.Do(req)
		tries++
	}

	// maximum retries exceeded
	if err != nil {
		// log error here
		return
	}

	// now the request was successful; do some work

	// close the body now
	if err = resp.Body.Close(); err != nil {
		// log error
	}
}