跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • golang 的 http 请求, transport.CancelRequest 与 client.Timeout 有冲突
未分類
19 1 月 2020

golang 的 http 请求, transport.CancelRequest 与 client.Timeout 有冲突

golang 的 http 请求, transport.CancelRequest 与 client.Timeout 有冲突

資深大佬 : howellz 3

两个需求:

  1. 用户可以随时终止请求。
  2. 用户可以修改超时值,比如 20s ;

对于第一个需求,设置了 client.Transport,并在合适的位置调用其 CancelRequest()接口; 对于第二个需求,设置了 client.Timeout ;

但是调试中发现,如果设置了 client.Timeout,则 Transport.CancelRequest()就不再起效。 注释掉 Timeout 就可以生效。

代码如下:

package main  import (  "fmt"  "net/http"  "time" )  func main() {  trans := &http.Transport{}  client := &http.Client{   Transport: trans,   Timeout:   time.Second * (30), // 这一行不注释就无法 CancelRequest  }  req, err := http.NewRequest("GET", "https://www.google.com", nil)  if err != nil {   panic(err)  }   go func() {   time.Sleep(time.Second * time.Duration(1))   fmt.Printf("%v: abortn", time.Now())   trans.CancelRequest(req)  }()   fmt.Printf("%v: start ...n", time.Now())  _, err = client.Do(req)  fmt.Printf("%v: donen", time.Now())  if err != nil {   fmt.Println(err.Error())  } } 

请问我该怎么办?

大佬有話說 (4)

  • 主 資深大佬 : howellz

    对了,自己不希望用 Timeou 来调用 CanceRequest,还是希望用 client 自己的 timeout 可以么?

  • 資深大佬 : guonaihong

    了解下 WithContext 。我在 gout 里面的超时就是用这个 API 实现的。context 可超时取消,可以调用 cancel 取消。
    这是官方 WithContext 的文档
    https://golang.google.cn/pkg/net/http/#Request.WithContext

    ## 这是 gout 里面使用 WithContext 的例子
    https://github.com/guonaihong/gout/blob/master/_example/05b-cancel.go

  • 資深大佬 : SingeeKing

    Deprecated: Use Request.WithContext to create a request with a cancelable context instead

  • 資深大佬 : reus

    https://gist.github.com/reusee/ba2a6f44fec5d70c81dcc51b6a71e744

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具