1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
package main
import (
"io/ioutil"
"log"
"net/http"
"time"
"github.com/rafaeljesus/retry-go"
)
var (
attempts = 3 //最大重试次数
sleepTime = time.Second * 2 //重试延迟时间
)
func main() {
_, err := retry.DoHTTP(func() (*http.Response, error) {
return makeRequest()
}, attempts, sleepTime)
if err != nil {
log.Print("retry.DoHTTP Failed")
return
}
log.Print("retry.DoHTTP OK")
}
// 发送http请求
func makeRequest() (*http.Response, error) {
client := http.Client{
Timeout: 2 * time.Second, // 设置请求超时时间
}
req, err := client.Get("https://www.baidu2.com") // 模拟不存在的url请求
if err != nil {
log.Printf(err.Error())
return nil, err
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf(err.Error())
return nil, err
}
log.Printf("响应数据 %v\\n", string(body))
defer req.Body.Close()
res := &http.Response{}
return res, nil
}
|