-
Notifications
You must be signed in to change notification settings - Fork 40
/
request.go
102 lines (92 loc) · 2.5 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
96
97
98
99
100
101
102
package model
import (
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/bububa/oceanengine/marketing-api/enum"
"github.com/bububa/oceanengine/marketing-api/util"
)
// PostRequest post request interface
type PostRequest interface {
// Encode encode request to bytes
Encode() []byte
}
// GetRequest get request interface
type GetRequest interface {
// Encode encode request to string
Encode() string
}
// UploadField multipart/form-data post request field struct
type UploadField struct {
// Key field key
Key string
// Value field value
Value string
// Reader upload file reader
Reader io.Reader
}
// UploadRequest multipart/form-data reqeust interface
type UploadRequest interface {
// Encode encode request to UploadFields
Encode() []UploadField
}
// ConversionRequest
type ConversionRequest interface {
PostRequest
Sign(req *http.Request, content []byte) (string, error)
GetAppAccessToken() string
}
// TrackRequest
type TrackRequest interface {
ConversionRequest
RequestURI() string
}
// CredentialSign implement ConvertionRequest interface
func CredentialSign(req *http.Request, content []byte, privateKey *rsa.PrivateKey, credential enum.Credential) (string, error) {
// get stringToSign
method := req.Method
pathAndQuery := req.URL.Path
// 在path末尾加上'/'
if pathAndQuery == "" || pathAndQuery[len(pathAndQuery)-1] != '/' {
pathAndQuery = pathAndQuery + "/"
}
if req.URL.RawQuery != "" {
pathAndQuery = pathAndQuery + "?" + req.URL.RawQuery
}
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
contentHash := getContentHashBase64(content)
buf := util.GetBufferPool()
buf.WriteString(strings.ToUpper(method))
buf.WriteByte('\n')
buf.WriteString(pathAndQuery)
buf.WriteByte('\n')
buf.WriteString(timestamp)
buf.WriteByte('\n')
buf.WriteString(contentHash)
signBytes, err := util.SignWithPrivateKey(buf.Bytes(), privateKey)
util.PutBufferPool(buf)
if err != nil {
return "", err
}
signature := base64.StdEncoding.EncodeToString(signBytes)
builder := util.GetStringsBuilder()
builder.WriteString("credential=")
builder.WriteString(string(credential))
builder.WriteString("×tamp=")
builder.WriteString(timestamp)
builder.WriteString("&signature=")
builder.WriteString(signature)
token := builder.String()
util.PutStringsBuilder(builder)
return token, nil
}
func getContentHashBase64(content []byte) string {
hasher := sha256.New()
hasher.Write(content)
return base64.StdEncoding.EncodeToString(hasher.Sum(nil))
}