-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpanda.go
298 lines (231 loc) · 7.48 KB
/
panda.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
Package panda implements PandaStream API as outlined in http://www.pandastream.com/docs/api
Public functions defined are:
Init(AccessKey string, SecretKey string, CloudId string, ApiHost string, ApiPort int)
ApiURL() string
Get(path string, data map[string]string) (string, error)
Post(path string, data map[string]string) (string, error)
Put(path string, data map[string]string) (string, error)
Delete(path string, data map[string]string) (string, error)
*/
package panda
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
)
const ApiHost string = "api.pandastream.com"
const ApiPort int = 443
const ApiVersion = 2
type PandaApi struct {
AccessKey string
SecretKey string
CloudId string
ApiHost string
ApiPort int
ApiVersion int
transport *http.Transport
client *http.Client
}
type PandaApiInterface interface {
Init(AccessKey string, SecretKey string, CloudId string, ApiHost string, ApiPort int)
apiProtocol() string
apiPath() string
ApiURL() string
generateTimestamp() string
signedParams(http_verb string, path string, data map[string]string, timestamp string) (map[string]string, error)
generateSignature(http_verb string, request_uri string, params map[string]string) (string, error)
canonicalQS(m map[string]string) string
httpRequest(http_verb string, path string, data map[string]string) (string, error)
Get(path string, data map[string]string) (string, error)
Post(path string, data map[string]string) (string, error)
Put(path string, data map[string]string) (string, error)
Delete(path string, data map[string]string) (string, error)
}
func Version() string {
return "0.1.0"
}
func (api PandaApi) generateTimestamp() string {
timenow := time.Now().UTC()
return timenow.Format("2006-01-02T15:04:05.999999+00:00")
}
func URLEscape(s string) string {
new_s := strings.Replace(url.QueryEscape(s), "%7E", "~", -1)
new_s = strings.Replace(new_s, " ", "%20", -1)
new_s = strings.Replace(new_s, "/", "%2F", -1)
return new_s
}
func (api PandaApi) apiProtocol() string {
if api.ApiPort == 443 {
return "https"
} else {
return "http"
}
}
func (api PandaApi) apiPath() string {
return "/v" + strconv.Itoa(api.ApiVersion)
}
// returns current base API URL
func (api PandaApi) ApiURL() string {
return api.apiProtocol() + "://" + api.ApiHost + api.apiPath()
}
// sign the request with signature as outlined in the API docs
func (api PandaApi) signedParams(http_verb string, path string, data map[string]string, timestamp string) (map[string]string, error) {
AuthParams := map[string]string{"cloud_id": api.CloudId, "access_key": api.AccessKey, "timestamp": timestamp}
for k, v := range data {
AuthParams[URLEscape(k)] = URLEscape(v)
}
AdditionalParams := make(map[string]string)
for k, v := range AuthParams {
AdditionalParams[k] = v
}
delete(AdditionalParams, "file")
signature, err := api.generateSignature(http_verb, path, AdditionalParams)
if err != nil {
return nil, err
}
AuthParams["signature"] = signature
return AuthParams, nil
}
// build POST request
func (api PandaApi) buildPostRequest(path string, params map[string]string, file string, FileType string) (*http.Request, error) {
boundary, end := "^{---panda---}v", "\r\n"
fp, err := os.OpenFile(file, os.O_RDONLY, 0)
if err != nil {
return nil, err
}
fstat, err := fp.Stat()
if err != nil {
return nil, err
}
FileSize := fstat.Size()
BodyHeader := bytes.NewBuffer(nil)
for k, v := range params {
BodyHeader.WriteString(fmt.Sprintf("--%s%s", boundary, end))
BodyHeader.WriteString(fmt.Sprintf("Content-Disposition: form-data; name=\"%s\"%s%s", k, end, end))
BodyHeader.WriteString(fmt.Sprintf("%s%s", v, end))
}
BodyHeader.WriteString(fmt.Sprintf("--%s%s", boundary, end))
BodyHeader.WriteString(fmt.Sprintf("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"%s", file, file, end))
BodyHeader.WriteString(fmt.Sprintf("Content-Type: %s%s%s", FileType, end, end))
BodyFooter := bytes.NewBufferString(end + "--" + boundary + "--" + end)
r, w := io.Pipe()
go func() {
BodySlices := []io.Reader{BodyHeader, fp, BodyFooter}
for _, k := range BodySlices {
_, err = io.Copy(w, k)
if err != nil {
w.CloseWithError(err)
return
}
}
fp.Close()
w.Close()
}()
BodyLen := int64(BodyHeader.Len()) + FileSize + int64(BodyFooter.Len())
HttpHeader := make(http.Header)
HttpHeader.Add("Content-Type", "multipart/form-data; boundary="+boundary)
RealUrl, _ := url.Parse(path)
PostRequest := &http.Request{
Method: "POST",
URL: RealUrl,
Host: api.ApiHost,
Header: HttpHeader,
Body: r,
ContentLength: BodyLen,
}
return PostRequest, nil
}
// builds generic HTTP request
func (api PandaApi) httpRequest(http_verb string, path string, data map[string]string) (string, error) {
var HttpReq *http.Request
var err error
signedParams, err := api.signedParams(http_verb, path, data, api.generateTimestamp())
if err != nil {
return "", err
}
CanonicalQS := api.canonicalQS(signedParams)
var RequestURL string = api.ApiURL() + path + "?" + CanonicalQS
if file, ok := data["file"]; ok {
if strings.ToUpper(http_verb) == "POST" {
post_req, err := api.buildPostRequest(RequestURL, data, file, "application/octet-stream")
if err != nil {
return "", err
}
HttpReq = post_req
}
} else {
HttpReq, err = http.NewRequest(http_verb, RequestURL, nil)
}
resp, err := api.client.Do(HttpReq)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), err
}
// builds the required query string - the keys have to be sorted
func (api PandaApi) canonicalQS(m map[string]string) string {
var keys []string
var qs []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
qs = append(qs, URLEscape(k)+"="+URLEscape(m[k]))
}
return strings.Join(qs, "&")
}
// generates the signature using HMAC/SHA256
func (api PandaApi) generateSignature(http_verb string, request_uri string, params map[string]string) (string, error) {
qs := api.canonicalQS(params)
var s []string = []string{strings.ToUpper(http_verb), strings.ToLower(api.ApiHost), request_uri, qs}
string_to_sign := strings.Join(s, "\n")
mac := hmac.New(sha256.New, []byte(api.SecretKey))
mac.Write([]byte(string_to_sign))
gmac := mac.Sum(nil)
return strings.Trim(base64.StdEncoding.EncodeToString(gmac), " "), nil
}
func (api PandaApi) Get(path string, data map[string]string) (string, error) {
return api.httpRequest("GET", path, data)
}
func (api PandaApi) Post(path string, data map[string]string) (string, error) {
return api.httpRequest("POST", path, data)
}
func (api PandaApi) Put(path string, data map[string]string) (string, error) {
return api.httpRequest("PUT", path, data)
}
func (api PandaApi) Delete(path string, data map[string]string) (string, error) {
return api.httpRequest("DELETE", path, data)
}
// initialise the client
func (api *PandaApi) Init(AccessKey string, SecretKey string, CloudId string, ApiHost string, ApiPort int) {
api.transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
DisableCompression: false,
}
api.client = &http.Client{Transport: api.transport}
api.AccessKey = AccessKey
api.SecretKey = SecretKey
api.CloudId = CloudId
api.ApiHost = ApiHost
api.ApiPort = ApiPort
api.ApiVersion = ApiVersion
}