-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
180 lines (160 loc) · 4.25 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package panda
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
"time"
)
const (
HostUS = "api.pandastream.com"
HostEU = "api-eu.pandastream.com"
HostGCE = "api-gce.pandastream.com"
)
// ClientOptions hold credentials required for authenticating requests to the Panda Cloud
type ClientOptions struct {
CloudID string
AccessKey string
SecretKey string
Namespace string
Token string
}
var queryFixer = strings.NewReplacer("+", "%20", "%5B", "[", "%5D", "]", "%7E", "~")
// Client is capable of sending signed requests to the Panda Cloud
type Client struct {
Host string
Options *ClientOptions
HTTPClient *http.Client
}
func (cl *Client) hostPort() string {
if cl.Host != "" {
return cl.Host
}
return HostUS
}
func (cl *Client) host() string {
hp := cl.hostPort()
i := strings.Index(hp, ":")
if i < 0 {
return hp
}
return hp[:i]
}
func (cl *Client) namespace() string {
if cl.Options.Namespace == "" {
return "v2"
}
return cl.Options.Namespace
}
func (cl *Client) httpclient() *http.Client {
if cl.HTTPClient != nil {
return cl.HTTPClient
}
return http.DefaultClient
}
func (cl *Client) addAuthParams(v url.Values, t time.Time) {
v.Set("access_key", cl.Options.AccessKey)
v.Set("cloud_id", cl.Options.CloudID)
v.Set("timestamp", t.Format(time.RFC3339Nano))
}
func (cl *Client) fixQuery(s string) string {
return queryFixer.Replace(s)
}
func (cl *Client) buildSignature(v url.Values, method, u string) (sign string, err error) {
toSign := fmt.Sprintf("%s\n%s\n%s\n%s", method, cl.host(), u, cl.fixQuery(v.Encode()))
mac := hmac.New(sha256.New, []byte(cl.Options.SecretKey))
if _, err = mac.Write([]byte(toSign)); err == nil {
sign = base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
return
}
func (cl *Client) buildURL(v url.Values, urlPath string) *url.URL {
scheme := "http"
if strings.HasSuffix(cl.hostPort(), ":443") {
scheme = "https"
}
return &url.URL{
Scheme: scheme,
Host: cl.hostPort(),
Path: path.Join(cl.namespace(), urlPath),
RawQuery: v.Encode(),
}
}
func (cl *Client) do(method, path, cntType string,
params url.Values, r io.Reader) (b []byte, err error) {
if params == nil {
params = url.Values{}
}
if err = cl.authParams(method, path, params); err != nil {
return
}
req, err := http.NewRequest(method, cl.buildURL(params, path).String(), r)
if err != nil {
return
}
req.Header.Set("Content-Type", cntType)
resp, err := cl.httpclient().Do(req)
if err != nil {
return
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
e := &Error{Code: resp.StatusCode}
if err = json.Unmarshal(b, e); err != nil {
return nil, e
}
err = e
}
return
}
func (cl *Client) authParams(method, path string, params url.Values) error {
if cl.Options.Token != "" {
params.Add("token", cl.Options.Token)
return nil
}
return cl.SignParams(method, path, params)
}
// SignParams signs given parameters by adding required authorization
// fields and values. Params cannot be nil.
func (cl *Client) SignParams(method, path string, params url.Values) error {
if params == nil {
panic("params cannot be nil!")
}
cl.addAuthParams(params, time.Now().UTC())
s, err := cl.buildSignature(params, method, path)
if err != nil {
return err
}
params.Set("signature", s)
return nil
}
// Get issues a signed GET request to the Panda Cloud
func (cl *Client) Get(url string, params url.Values) ([]byte, error) {
return cl.do("GET", url, "", params, nil)
}
// Post issues a signed POST request to the Panda Cloud and creates content based on
// the given params
func (cl *Client) Post(url, cntType string, params url.Values, r io.Reader) ([]byte, error) {
return cl.do("POST", url, cntType, params, r)
}
// Put issues a signed PUT request to the Panda Cloud and updates object according to
// given params
func (cl *Client) Put(url, cntType string, params url.Values, r io.Reader) ([]byte, error) {
return cl.do("PUT", url, cntType, params, r)
}
// Delete issues a signed DELETE request to the Panda Cloud and deletes content under
// the given url
func (cl *Client) Delete(url string) ([]byte, error) {
return cl.do("DELETE", url, "", nil, nil)
}