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()函数来进行超时控制
网友评论