Skip to content

Commit ca83c6c

Browse files
committed
fix: 优化发送请求方法,当出现超时时处理报错,不会中断服务
优化发送请求方法,当出现超时时处理报错,不会中断服务
1 parent ecc6bc7 commit ca83c6c

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

auth/client.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
package auth
22

33
import (
4+
"context"
45
"encoding/json"
56
"errors"
67
"fmt"
78
"io"
89
"net/http"
910
"strings"
11+
"time"
1012

1113
"github.com/sirupsen/logrus"
1214
)
@@ -16,14 +18,20 @@ type Client struct {
1618

1719
// getParsedResponse gets response data from gitee
1820
func getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) error {
21+
client := &http.Client{
22+
Timeout: 30 * time.Second, // 整个请求的最大超时时间
23+
}
1924
req, err := http.NewRequest(method, path, body)
2025
if err != nil {
2126
panic(err)
2227
}
2328
req.Header = header
24-
response, err := http.DefaultClient.Do(req)
29+
response, err := client.Do(req)
2530
if err != nil {
26-
panic(err)
31+
if errors.Is(err, context.DeadlineExceeded) {
32+
return fmt.Errorf("请求超时: %w", err)
33+
}
34+
return fmt.Errorf("请求执行失败: %w", err)
2735
}
2836
defer response.Body.Close()
2937

0 commit comments

Comments
 (0)