0

http.Response.Write causes 'use of closed network connection' error after the closing of the net.Conn what the http.Response has received data from. E.g. I need to do something like this:

func Do(req *http.Request) *http.Response {
    // ...

    req.Write(conn)

    var r = bufio.NewReader(conn)
    var resp = http.ReadResponse(r, req)
    conn.Close()

    return resp
}

//...
var resp = Do(req)
resp.Write(anotherConn) // here is the error

but the last line gives the above error. You can say that an obvious solution is the conn.Close after resp.Write but the reason of that I do like this is that Do must write the req to the conn that it creates itself and then only return the resp.

The only thing that interests me is that how the conn and the req are related. I thought that response saves all the received data in itself in ReadResponse and then does not depend on connection that it has received data from. But it does not seem like this.

2
  • 2
    I'm only guessing but the body of the response is probably read lazily from the connection, so if that's the case you could first read the whole body into some buffer then close the connection, then set the read body to the response's Body field, and then continue? Commented Apr 9, 2020 at 12:55
  • 1
    ... if you check the documentation, it does seem to suggest that that is the case: "The response body is streamed on demand as the Body field is read. " Commented Apr 9, 2020 at 13:13

1 Answer 1

3

ReadResponse reads the status line and headers, then exposes the response body in Respons.Body, which accesses the underlying connection directly to read the body on the fly, rather than loading the entire body (which could be many megabytes) into memory. This allows the implementation to be as efficient as possible, e.g. stream processing the body rather than loading all of it into memory and then processing it.

Per the docs:

The response body is streamed on demand as the Body field is read. If the network connection fails or the server terminates the response, Body.Read calls return an error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.