-
Notifications
You must be signed in to change notification settings - Fork 0
/
qiniumac.go
75 lines (59 loc) · 1.68 KB
/
qiniumac.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
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"io"
"io/ioutil"
"net/http"
"sort"
)
const qiniuHeaderPrefix = "X-Qiniu-"
func includeBody(req *http.Request, ctType string) bool {
return req.ContentLength != 0 && req.Body != nil && ctType != "" && ctType != "application/octet-stream"
}
// ---------------------------------------------------------------------------------------
type sortByHeaderKey []string
func (p sortByHeaderKey) Len() int { return len(p) }
func (p sortByHeaderKey) Less(i, j int) bool { return p[i] < p[j] }
func (p sortByHeaderKey) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func signQiniuHeaderValues(header http.Header, w io.Writer) {
var keys []string
for key := range header {
if len(key) > len(qiniuHeaderPrefix) && key[:len(qiniuHeaderPrefix)] == qiniuHeaderPrefix {
keys = append(keys, key)
}
}
if len(keys) == 0 {
return
}
if len(keys) > 1 {
sort.Sort(sortByHeaderKey(keys))
}
for _, key := range keys {
io.WriteString(w, "\n"+key+": "+header.Get(key))
}
}
// SignRequest calculate
func SignRequest(sk []byte, req *http.Request) ([]byte, error) {
h := hmac.New(sha1.New, sk)
u := req.URL
data := req.Method + " " + u.Path
if u.RawQuery != "" {
data += "?" + u.RawQuery
}
io.WriteString(h, data+"\nHost: "+req.Host)
ctType := req.Header.Get("Content-Type")
if ctType != "" {
io.WriteString(h, "\nContent-Type: "+ctType)
}
signQiniuHeaderValues(req.Header, h)
io.WriteString(h, "\n\n")
if includeBody(req, ctType) {
bodyBytes, _ := ioutil.ReadAll(req.Body)
req.Body.Close() // must close
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
h.Write(bodyBytes)
}
return h.Sum(nil), nil
}