-
Notifications
You must be signed in to change notification settings - Fork 31
/
request.go
87 lines (72 loc) · 1.88 KB
/
request.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
package awsping
import (
"net"
"net/http"
"time"
)
// RequestType describes a type for a request type
type RequestType int
const (
// RequestTypeHTTP is HTTP type of request
RequestTypeHTTP RequestType = iota
// RequestTypeTCP is TCP type of request
RequestTypeTCP
)
// Requester is an interface to do a network request
type Requester interface {
Do(ua, url string, reqType RequestType) (time.Duration, error)
}
// AWSHTTPRequester is an interface for HTTP requests
type AWSHTTPRequester interface {
Do(req *http.Request) (*http.Response, error)
}
// AWSTCPRequester is an interface for TCP requests
type AWSTCPRequester interface {
Dial(network, address string) (net.Conn, error)
}
// AWSRequest implements Requester interface
type AWSRequest struct {
httpClient AWSHTTPRequester
tcpClient AWSTCPRequester
}
// NewAWSRequest creates a new instance of AWSRequest
func NewAWSRequest() *AWSRequest {
return &AWSRequest{
httpClient: &http.Client{},
tcpClient: &net.Dialer{},
}
}
// DoHTTP does HTTP request for a URL by User-Agent (ua)
func (r *AWSRequest) DoHTTP(ua, url string) (time.Duration, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return 0, err
}
req.Header.Set("User-Agent", ua)
start := time.Now()
resp, err := r.httpClient.Do(req)
latency := time.Since(start)
if err != nil {
return 0, err
}
defer resp.Body.Close()
return latency, nil
}
// DoTCP does TCP request to the Addr
func (r *AWSRequest) DoTCP(_, addr string) (time.Duration, error) {
start := time.Now()
conn, err := r.tcpClient.Dial("tcp", addr)
if err != nil {
return 0, err
}
l := time.Since(start)
defer conn.Close()
return l, nil
}
// Do does a request. Type of request depends on reqType
func (r *AWSRequest) Do(ua, url string, reqType RequestType) (time.Duration, error) {
if reqType == RequestTypeHTTP {
return r.DoHTTP(ua, url)
}
return r.DoTCP(ua, url)
}