首页 > go的net/http中,client的timeout是否存在问题?

go的net/http中,client的timeout是否存在问题?

type Client struct {
    // Transport specifies the mechanism by which individual
    // HTTP requests are made.
    // If nil, DefaultTransport is used.
    Transport RoundTripper

    // CheckRedirect specifies the policy for handling redirects.
    // If CheckRedirect is not nil, the client calls it before
    // following an HTTP redirect. The arguments req and via are
    // the upcoming request and the requests made already, oldest
    // first. If CheckRedirect returns an error, the Client's Get
    // method returns both the previous Response and
    // CheckRedirect's error (wrapped in a url.Error) instead of
    // issuing the Request req.
    //
    // If CheckRedirect is nil, the Client uses its default policy,
    // which is to stop after 10 consecutive requests.
    CheckRedirect func(req *Request, via []*Request) error

    // Jar specifies the cookie jar.
    // If Jar is nil, cookies are not sent in requests and ignored
    // in responses.
    Jar CookieJar

    // Timeout specifies a time limit for requests made by this
    // Client. The timeout includes connection time, any
    // redirects, and reading the response body. The timer remains
    // running after Get, Head, Post, or Do return and will
    // interrupt reading of the Response.Body.
    //
    // A Timeout of zero means no timeout.
    //
    // The Client's Transport must support the CancelRequest
    // method or Client will return errors when attempting to make
    // a request with Get, Head, Post, or Do. Client's default
    // Transport (DefaultTransport) supports CancelRequest.
    Timeout time.Duration
}

以上是部分源码。之前有同学问,client的timeout存在问题,请问有其他人遇见了同样的问题么?


题主的问题很有些莫名其妙,只说有问题但没说明究竟什么问题……不过我还是尝试答一下吧。

如果要说 Timeout 有什么问题,需要注意注释文档里的这句话。

A Timeout of zero means no timeout.

如果你要发送很多请求,这个默认特性会害死人,在网络有问题的时候它会造成 Client 生成的 RequestResponse 对象以及相关 goroutine 得不到释放,逐渐就吃满内存导致程序挂掉。

所以使用 go 的时候最好不要直接使用 http.Get 之类的函数,这些都是使用默认 Client 的,没有 Timeout,如果非要用,那就把 http.DefaultClientTimeout 设置上吧。

最后,我还是预感题主要问的问题跟我说的其实不搭界,啊,题主快现身把你的题目写清楚吧~


指的是 use of closed network connection 这个问题么?这个有遇到过哦,见链接:https://github.com/golang/go/issues/9405。

【热门文章】
【热门文章】