-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgreq.go
More file actions
82 lines (68 loc) · 1.89 KB
/
greq.go
File metadata and controls
82 lines (68 loc) · 1.89 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Package greq is a simple http client request builder, support batch requests.
package greq
import (
"io"
"net"
"net/http"
"time"
)
// DefaultDoer for request.
var DefaultDoer = http.DefaultClient
// HandleFunc for the Middleware
type HandleFunc func(r *http.Request) (*Response, error)
// AfterSendFn callback func
type AfterSendFn func(resp *Response, err error)
// RetryChecker function type for checking if a request should be retried
type RetryChecker func(resp *Response, err error, attempt int) bool
// DefaultRetryChecker is the default retry condition checker
// It retries on:
// - Network errors (err != nil)
// - 5xx server errors
// - 429 Too Many Requests
func DefaultRetryChecker(resp *Response, err error, attempt int) bool {
// Retry on network errors
if err != nil {
return true
}
// Retry on server errors (5xx)
if resp.StatusCode >= 500 && resp.StatusCode < 600 {
return true
}
// Retry on rate limiting (429)
if resp.StatusCode == 429 {
return true
}
return false
}
// RequestCreator interface
type RequestCreator interface {
NewRequest(method, target string, body io.Reader) *http.Request
}
// RequestCreatorFunc func
type RequestCreatorFunc func(method, target string, body io.Reader) *http.Request
// Must return response, if error will panic
func Must(w *Response, err error) *Response {
if err != nil {
panic(err)
}
return w
}
// NewTransport create new http transport
func NewTransport(onCreate func(ht *http.Transport)) *http.Transport {
transport := &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 500,
MaxConnsPerHost: 200,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if onCreate != nil {
onCreate(transport)
}
return transport
}