Goroutine超时 [英] Goroutine Timeout

查看:56
本文介绍了Goroutine超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type Response struct {
  data   interface{}
  status bool
}

func Find() (interface{}, bool) {
  ch := make(chan Response, 1)

  go func() {
    data, status := findCicCode()
    ch <- Response{data: data, status: status}
  }()

  select {
  case response := <-ch:
    return response.data, response.status
  case <-time.After(50 * time.Millisecond):
    return "Request timed out", false
  }
}

所以,我有以上功能.基本上, findCicCode()函数调用在内部对外部服务进行了3次http调用.我在这里为这3个http呼叫添加了组合超时.我不能将个人超时设置为我的情况.但是,如果超过超时时间,它仍然会在后台进行api调用.

So, I have above function. Basically findCicCode() function call makes 3 http calls internally to external services. I have added combined timeout here for those 3 http calls. Can't put individual timeout in my case. But It still makes api calls in background if it exceeds timeout.

我不确定这里是否存在goroutine泄漏.如果超时,是否可以取消这些https请求?

I am not sure if there is goroutine leak here. Is there a way to cancel those https requests if there is timeout?

推荐答案

您可以使用

You control cancelation of http requests with a context.Context.

// create a timeout or cancelation context to suit your requirements
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

req, err := http.NewRequest("GET", location, nil)

// add the context to each request and they will be canceled in unison
resp, err := http.Do(req.WithContext(ctx))

这篇关于Goroutine超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆