policy.go 2.5 KB
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)
}