美文网首页golang 编程笔记
【golang】context上下文与http请求妙用

【golang】context上下文与http请求妙用

作者: dongzd | 来源:发表于2020-03-12 09:43 被阅读0次

1.在后端服务开发中,如过一个HTTP请求,请求一致占用,将会带来大的性能影响,所以需要为每个请求加上超时设置
2.在go语言中利用context进行上下文控制,要想达到精确时间控制,如下:

ctx, cancel := context.WithCancel(context.Background())
duration := 5 * time.Second
tm := time.AfterFunc(duration, func() {
    res.Error = fmt.Sprintf("Timeout; %s", res.Error)
    cancel()
})
req, err := request(m.Config.URL, data)
if err != nil {
    return res, fmt.Errorf("Execute: %s ", err)
}
req = req.WithContext(ctx)
resp, err := http.DefaultClient.Do(req)

3.同时我们也可以利用context的context.WithDeadline()函数来进行超时控制

相关文章

网友评论

    本文标题:【golang】context上下文与http请求妙用

    本文链接:https://www.haomeiwen.com/subject/rlxyjhtx.html