douxian3170 2018-07-07 12:07
浏览 81
已采纳

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
  }
}

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.

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

  • 写回答

2条回答 默认 最新

  • douxiangshi6568 2018-07-07 13:14
    关注

    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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误