dream_wu2015 2014-10-29 14:39
浏览 53
已采纳

Go如何处理HTTP保持活动状态?

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.

  • 写回答

1条回答 默认 最新

  • doupang3062 2014-10-29 14:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog