-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
110 lines (94 loc) · 2.44 KB
/
client.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package httpmon
import (
"fmt"
"net"
"net/http"
"time"
)
func NewHttpClient(timeout Timeout) HttpClient {
return &DefaultHttpClient{
GoRequestBuilder: buildRequest,
GoHttpClient: defaultGoHttpClient(timeout),
}
}
type DefaultHttpClient struct {
GoRequestBuilder
GoHttpClient
}
func (client *DefaultHttpClient) Run(request HttpRequest) (HttpTest, error) {
req, err := client.GoRequestBuilder(request)
if err != nil {
return nil, err
}
start := time.Now()
response, err := client.GoHttpClient.Run(req)
if err != nil {
return nil, err
}
finish := time.Now()
duration := finish.Sub(start)
return &DefaultHttpTest{
Status: HttpResponseStatus(response.StatusCode),
Header: response.Header,
ResponseTime: ResponseTime(duration),
}, nil
}
type GoRequestBuilder func(request HttpRequest) (*http.Request, error)
func buildRequest(request HttpRequest) (*http.Request, error) {
req, err := http.NewRequest(string(request.requestMethod()), string(request.requestURL()), request.requestBody())
if err != nil {
return nil, &GoStandardError{
Tag: fmt.Sprintf("BuildRequest(%s)", request),
Original: err,
}
}
hs := req.Header
header := request.requestHeader()
for n, values := range header {
for _, v := range values {
hs.Add(string(n), string(v))
}
}
return req, err
}
type GoStandardError struct {
Tag string
Original error
}
func (err *GoStandardError) Error() string {
return fmt.Sprintf("%s: (%v)", err.Tag, err.Original)
}
func (err *GoStandardError) IsTimeout() bool {
if gerr, ok := err.Original.(net.Error); ok {
return gerr.Timeout()
}
return false
}
// GoHttpClient limits go's standard http client only to its Do function.
type GoHttpClient interface {
Run(r *http.Request) (*http.Response, error)
}
// DefaultGoHttpClient is default implementation of GoHttpClient
type DefaultGoHttpClient struct {
Client *http.Client
}
// Run calls Do function of go's http client.
func (client *DefaultGoHttpClient) Run(r *http.Request) (*http.Response, error) {
response, err := client.Client.Do(r)
if err != nil {
return nil, &GoStandardError{
Tag: fmt.Sprintf("GoHttpClient#Run#%s(%s)", r.URL, r.Method),
Original: err,
}
}
return response, nil
}
// defaultGoHttpClient creates GoHttpClient with given timeout
func defaultGoHttpClient(timeout Timeout) GoHttpClient {
client := http.Client{
Timeout: time.Duration(timeout),
}
return &DefaultGoHttpClient{
Client: &client,
}
}