-
Notifications
You must be signed in to change notification settings - Fork 23
/
http.go
94 lines (81 loc) · 1.58 KB
/
http.go
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
83
84
85
86
87
88
89
90
91
92
93
94
/*
Various http helpers and utilities
*/
package goexpose
import (
"io"
"net"
"net/http"
"time"
)
/*
Requester
makes http requests
*/
const (
DEFAULT_TIMEOUT = 10 * time.Second
)
/*
RequesterSetFunc is callback function to be called in Set method.
*/
type RequesterSetFunc func(r *Requester)
/*
NewRequester returns new requester instance
*/
func NewRequester(funcs ...RequesterSetFunc) (result *Requester) {
result = &Requester{}
result.Set(WithTimeout(DEFAULT_TIMEOUT))
if len(funcs) > 0 {
result.Set(funcs...)
}
return
}
/*
Making requests
*/
type Requester struct {
timeout time.Duration
client *http.Client
}
/*
Do performs request and returns response or error
*/
func (r *Requester) DoRequest(req *http.Request) (resp *http.Response, err error) {
return r.client.Do(req)
}
/*
DoNew creates new request and sends it
*/
func (r *Requester) DoNew(method string, url string, body io.Reader) (req *http.Request, resp *http.Response, err error) {
if req, err = http.NewRequest(method, url, body); err != nil {
return
}
resp, err = r.client.Do(req)
return
}
/*
With is used to change values directly from constructors
*/
func (r *Requester) Set(funcs ...RequesterSetFunc) *Requester {
for _, fn := range funcs {
fn(r)
}
return r
}
/*
Set functions
*/
func WithTimeout(timeout time.Duration) RequesterSetFunc {
return func(r *Requester) {
r.timeout = timeout
r.client = &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: r.timeout,
//KeepAlive: 30 * time.Second,
}).Dial,
//TLSHandshakeTimeout: secs * time.Second,
},
}
}
}