dastan
dastan

Reputation: 1136

How does Go deal with HTTP keep-alive?

I understand the rule that, if client and server both support persistent connection, they can use it through a Connection:keep-alive header in the first request. After that, both client and server will still keep the underlying TCP connection open when they are done with the first request/response, and then use the same connection in the following requests/responses.

What I'm not clear about is the programming model. Consider the following client code in go:

resp, _ := client.Get("http://www.stackoverflow.com")
// do some other things
resp, _ = client.Get("http://www.stackoverflow.com/questions")

As far as I know, keep-alive is the default strategy in HTTP/1.1.

Q1: Do these two requests use the same TCP connection?

On the server side:

When one request comes, the Go HTTP framework dispatches it to a handler, then due to keep-alive, the framework should prepare for the next request on the same TCP connection. However I don't see any block-mode read code in a handler. So,

Q2: Does the Go HTTP framework use some kind of non-block mode to deal with keep-alive?

I mean, a handler will not block for reading, but just return when done with a request, then the framework will poll each non-block TCP connection, if one of them has data arrive, it dispatches it to an associated handler, and so on. Only when the request has a header of Connection:Close, the framework will close the TCP connection when the handler returns.

Upvotes: 4

Views: 6611

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109347

Q1: Do these two requests use the same TCP connection?

Yes, if the connection wasn't closed by the server, the http.Transport can re-use the connection in the default configuration.

Q2: Does the go http framework use some kind of non-block mode to deal with keep-alive?

The go HTTP Server handles keepalive connections be default. There's no such thing as a HTTP "non-block mode". It handles requests and responses on a single connection in a serial manner as described by the HTTP specification.

Upvotes: 3

Related Questions