policy.go
2.5 KB
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
package oss
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"hash"
"io"
"time"
)
type PolicyToken struct {
AccessKeyId string `json:"accessid"`
Host string `json:"host"`
Expire int64 `json:"expire"`
Signature string `json:"signature"`
Policy string `json:"policy"`
Directory string `json:"dir"`
Callback string `json:"callback"`
}
type PolicyConfigStruct struct {
Expiration string `json:"expiration"`
Conditions [][]string `json:"conditions"`
}
type CallbackParam struct {
CallbackUrl string `json:"callbackUrl"`
CallbackBody string `json:"callbackBody"`
CallbackBodyType string `json:"callbackBodyType"`
}
var (
// 用户上传文件时指定的文件夹。
upload_dir = "demo/"
)
func GetPolicyToken() string {
now := time.Now().Unix()
expire_end := now + 30
var tokenExpire = time.Unix(expire_end, 0).Format("2006-01-02T15:04:05Z")
//create post policy json
var policyConfig PolicyConfigStruct
policyConfig.Expiration = tokenExpire
var condition []string
condition = append(condition, "starts-with")
condition = append(condition, "$key")
condition = append(condition, upload_dir)
policyConfig.Conditions = append(policyConfig.Conditions, condition)
ossConfig := NewOssConfig()
//calucate signature
result, err := json.Marshal(policyConfig)
debyte := base64.StdEncoding.EncodeToString(result)
h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(ossConfig.accessKey))
io.WriteString(h, debyte)
signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
var callbackParam CallbackParam
callbackParam.CallbackUrl = ossConfig.callbackUrl
callbackParam.CallbackBody = "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}"
callbackParam.CallbackBodyType = "application/x-www-form-urlencoded"
callback_str, err := json.Marshal(callbackParam)
if err != nil {
fmt.Println("callback json err:", err)
}
callbackBase64 := base64.StdEncoding.EncodeToString(callback_str)
var policyToken PolicyToken
policyToken.AccessKeyId = ossConfig.accessID
policyToken.Host = ossConfig.hostStr
policyToken.Expire = expire_end
policyToken.Signature = string(signedStr)
//TODO 文件夹另外处理
policyToken.Directory = upload_dir
policyToken.Policy = string(debyte)
policyToken.Callback = string(callbackBase64)
response, err := json.Marshal(policyToken)
if err != nil {
fmt.Println("json err:", err)
}
return string(response)
}