-
Notifications
You must be signed in to change notification settings - Fork 131
/
request.go
95 lines (81 loc) · 2.18 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
88
89
90
91
92
93
94
95
package sls
import (
"bytes"
"crypto/md5"
"fmt"
"net/http"
"net/http/httputil"
"encoding/json"
"io/ioutil"
"github.com/golang/glog"
)
// request sends a request to SLS.
func request(project *LogProject, method, uri string, headers map[string]string,
body []byte) (*http.Response, error) {
// The caller should provide 'x-log-bodyrawsize' header
if _, ok := headers["x-log-bodyrawsize"]; !ok {
return nil, fmt.Errorf("Can't find 'x-log-bodyrawsize' header")
}
// SLS public request headers
headers["Host"] = project.Name + "." + project.Endpoint
headers["Date"] = nowRFC1123()
headers["x-log-apiversion"] = version
headers["x-log-signaturemethod"] = signatureMethod
// Access with token
if project.SecurityToken != "" {
headers["x-acs-security-token"] = project.SecurityToken
}
if body != nil {
bodyMD5 := fmt.Sprintf("%X", md5.Sum(body))
headers["Content-MD5"] = bodyMD5
if _, ok := headers["Content-Type"]; !ok {
return nil, fmt.Errorf("Can't find 'Content-Type' header")
}
}
// Calc Authorization
// Authorization = "SLS <AccessKeyId>:<Signature>"
digest, err := signature(project, method, uri, headers)
if err != nil {
return nil, err
}
auth := fmt.Sprintf("SLS %v:%v", project.AccessKeyID, digest)
headers["Authorization"] = auth
// Initialize http request
reader := bytes.NewReader(body)
urlStr := fmt.Sprintf("https://%v.%v%v", project.Name, project.Endpoint, uri)
req, err := http.NewRequest(method, urlStr, reader)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Add(k, v)
}
if glog.V(1) {
dump, e := httputil.DumpRequest(req, true)
if e != nil {
glog.Info(e)
}
glog.Infof("HTTP Request:\n%v", string(dump))
}
// Get ready to do request
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
// Parse the sls error from body.
if resp.StatusCode != http.StatusOK {
err := &Error{}
buf, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(buf, err)
err.RequestID = resp.Header.Get("x-log-requestid")
return nil, err
}
if glog.V(1) {
dump, e := httputil.DumpResponse(resp, true)
if e != nil {
glog.Info(e)
}
glog.Infof("HTTP Response:\n%v", string(dump))
}
return resp, nil
}