forked from philchia/agollo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
86 lines (70 loc) · 1.73 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
package agollo
import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
)
var ErrorStatusNotOK = errors.New("http resp code not ok")
// this is a static check
var _ requester = (*httpRequester)(nil)
var _ requester = (*httpSignRequester)(nil)
type requester interface {
request(url string) ([]byte, error)
}
type httpRequester struct {
client *http.Client
}
func newHTTPRequester(client *http.Client) requester {
return &httpRequester{
client: client,
}
}
func (r *httpRequester) request(url string) ([]byte, error) {
resp, err := r.client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return ioutil.ReadAll(resp.Body)
}
// Discard all body if status code is not 200
_, _ = io.Copy(ioutil.Discard, resp.Body)
return nil, ErrorStatusNotOK
}
type httpSignRequester struct {
signature *signature
client *http.Client
}
func newHttpSignRequester(signature *signature, client *http.Client) requester {
return &httpSignRequester{
signature: signature,
client: client,
}
}
func (r *httpSignRequester) request(url string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
timestamp := r.signature.getTimestamp()
req.Header.Set(signHttpHeaderAuthorization, fmt.Sprintf(
signAuthorizationFormat,
r.signature.AppID,
r.signature.getAuthorization(url, timestamp),
))
req.Header.Set(signHttpHeaderTimestamp, timestamp)
resp, err := r.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return ioutil.ReadAll(resp.Body)
}
// Discard all body if status code is not 200
_, _ = io.Copy(ioutil.Discard, resp.Body)
return nil, ErrorStatusNotOK
}