Go + PostgreSQL + Valkey backend (cmd/internal/migrations), uni-app mobile frontend, PC web (web/), admin console (admin/), Android WebView container (android_project/). Build artifacts, node_modules, local env and debug screenshots excluded.
68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
package storage
|
||
|
||
import (
|
||
"crypto/hmac"
|
||
"crypto/sha1"
|
||
"encoding/base64"
|
||
"encoding/json"
|
||
"fmt"
|
||
"strings"
|
||
"time"
|
||
)
|
||
|
||
// QiniuPresigner 为七牛云/扩展存储签发直传 Token 与管理 URL
|
||
type QiniuPresigner struct {
|
||
Bucket string
|
||
AccessKey string
|
||
SecretKey string
|
||
UploadHost string // 如 https://upload.qiniup.com
|
||
PublicBase string // 如 http://qnycdn.mymoyu.top
|
||
}
|
||
|
||
// UploadPolicy 七牛上传策略
|
||
type UploadPolicy struct {
|
||
Scope string `json:"scope"`
|
||
Deadline int64 `json:"deadline"`
|
||
}
|
||
|
||
// SignUpload 生成客户端直传所需的信息(UploadURL, Token, Key)
|
||
func (q *QiniuPresigner) SignUpload(objectKey string, ttl time.Duration) (uploadURL, token string, formData map[string]string, err error) {
|
||
if ttl <= 0 {
|
||
ttl = 15 * time.Minute
|
||
}
|
||
deadline := time.Now().Add(ttl).Unix()
|
||
policy := UploadPolicy{
|
||
Scope: fmt.Sprintf("%s:%s", q.Bucket, objectKey),
|
||
Deadline: deadline,
|
||
}
|
||
|
||
b, err := json.Marshal(policy)
|
||
if err != nil {
|
||
return "", "", nil, fmt.Errorf("marshal policy: %w", err)
|
||
}
|
||
|
||
encodedPolicy := base64.URLEncoding.EncodeToString(b)
|
||
h := hmac.New(sha1.New, []byte(q.SecretKey))
|
||
h.Write([]byte(encodedPolicy))
|
||
encodedSign := base64.URLEncoding.EncodeToString(h.Sum(nil))
|
||
|
||
uploadToken := fmt.Sprintf("%s:%s:%s", q.AccessKey, encodedSign, encodedPolicy)
|
||
|
||
host := q.UploadHost
|
||
if host == "" {
|
||
host = "https://upload.qiniup.com"
|
||
}
|
||
|
||
return host, uploadToken, map[string]string{
|
||
"token": uploadToken,
|
||
"key": objectKey,
|
||
}, nil
|
||
}
|
||
|
||
// PublicURL 拼接 CDN 访问直链
|
||
func (q *QiniuPresigner) PublicURL(objectKey string) string {
|
||
base := strings.TrimRight(q.PublicBase, "/")
|
||
cleanKey := strings.TrimLeft(objectKey, "/")
|
||
return fmt.Sprintf("%s/%s", base, cleanKey)
|
||
}
|