How to set timeout for http.Get() requests in Golang?

后端 未结 7 1272
刺人心
刺人心 2020-12-22 16:15

I\'m making a URL fetcher in Go and have a list of URLs to fetch. I send http.Get() requests to each URL and obtain their response.

resp,fetch_e         


        
7条回答
  •  隐瞒了意图╮
    2020-12-22 17:02

    If you want to do it per request, err handling ignored for brevity:

    ctx, cncl := context.WithTimeout(context.Background(), time.Second*3)
    defer cncl()
    
    req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://google.com", nil)
    
    resp, _ := http.DefaultClient.Do(req)
    

提交回复
热议问题