登录
首页 >  Golang >  Go问答

HTTP 客户端超时返回随机错误信息

来源:stackoverflow

时间:2024-02-12 23:27:24 302浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《HTTP 客户端超时返回随机错误信息》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我有一个带有自定义 roundtripper 的 http 客户端,该客户端又使用 http.defaulttransport 来处理请求。 现在假设我有一个缓慢的服务器,需要很长时间才能响应,这会使我的 http 客户端超时并取消客户端。这是客户端的代码:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

type rt struct {
    roundTripper func(req *http.Request) (*http.Response, error)
}

func (r rt) RoundTrip(req *http.Request) (*http.Response, error) {
    return r.roundTripper(req)
}

func main() {

    c := http.Client{
        Timeout:   3 * time.Second,
        Transport:  rt{RoundTripper(http.DefaultTransport)},
    }
    resp, err := c.Get("http://127.0.0.1:9000")
    if err != nil {
        fmt.Println("err:", err)
    } else {
        body, err := ioutil.ReadAll(resp.Body)
        resp.Body.Close()
        fmt.Println(string(body), err)
    }

}
func RoundTripper(next http.RoundTripper) func(req *http.Request) (*http.Response, error) {
    return func(req *http.Request) (*http.Response, error) {
        resp, err := next.RoundTrip(req)
        if err != nil {
            return nil, fmt.Errorf("err: %w", err)
        }
        return resp, nil
    }
}

这里的问题是,我在超时时收到的错误随机是 net/http: request canceledcontext deadline been excessed 之一。

现在我知道它们在语义上应该是相同的,但我无法理解为什么它每次返回以及何时返回?

如果您想亲自尝试一下,这里是服务器代码。


解决方案


函数net/http/client.setrequestcancel()用于设置请求的取消。共有三种方式

  • 第二个将返回:net/http:请求已取消
  • 第三个将返回:超出上下文截止日期

因为两者使用相同的截止时间,time.now()+client.timeout。 所以根据运行时调度,通过这两种方法会随机取消请求。

https://github.com/golang/go/blob/master/src/net/http/transport.go#L2652

    case <-cancelChan:
        // return err: net/http: request
        pc.t.CancelRequest(req.Request) canceled
        cancelChan = nil
    case <-ctxDoneChan:
        // return err:
        pc.t.cancelRequest(req.Request, req.Context().Err())
        cancelChan = nil
        ctxDoneChan = nil

今天关于《HTTP 客户端超时返回随机错误信息》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>