fix: 七牛云私有 bucket 下载 URL 签名支持
对私有读 bucket,通过 HMAC-SHA1 签名生成带 e(过期时间)和 token(下载凭证) 参数的临时下载 URL,前端获取的素材 URL 和下载接口均返回签名 URL。 新增配置项 GEN2D_QINIU_URL_EXPIRE,默认 3600 秒。
This commit is contained in:
@@ -3,6 +3,9 @@ package service
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
@@ -65,15 +68,43 @@ func (s *StorageService) Upload(ctx context.Context, key string, data []byte) (s
|
||||
return "", fmt.Errorf("qiniu upload: %w", err)
|
||||
}
|
||||
|
||||
cdnURL := s.buildURL(key)
|
||||
cdnURL := s.buildBaseURL(key)
|
||||
l.Info("upload succeeded", "key", key, "url", cdnURL)
|
||||
return cdnURL, nil
|
||||
}
|
||||
|
||||
// GetDownloadURL 生成素材的下载 URL。
|
||||
// 公开 bucket 直接返回 CDN URL;私有 bucket 生成带签名的临时 URL。
|
||||
// 私有 bucket 生成带签名和过期时间的临时 URL。
|
||||
func (s *StorageService) GetDownloadURL(_ context.Context, key string) (string, error) {
|
||||
return s.buildURL(key), nil
|
||||
return s.signDownloadURL(key), nil
|
||||
}
|
||||
|
||||
// GetSignedURL 获取私有资源签名 URL(公开方法,供 handler 层使用)。
|
||||
func (s *StorageService) GetSignedURL(key string) string {
|
||||
return s.signDownloadURL(key)
|
||||
}
|
||||
|
||||
// signDownloadURL 生成七牛云私有资源下载签名 URL。
|
||||
// 格式:http://<domain>/<key>?e=<deadline>&token=<downloadToken>
|
||||
func (s *StorageService) signDownloadURL(key string) string {
|
||||
baseURL := s.buildBaseURL(key)
|
||||
|
||||
expire := s.cfg.URLExpire
|
||||
if expire <= 0 {
|
||||
expire = 3600
|
||||
}
|
||||
deadline := time.Now().Unix() + expire
|
||||
|
||||
signStr := fmt.Sprintf("%s?e=%d", baseURL, deadline)
|
||||
|
||||
mac := hmac.New(sha1.New, []byte(s.cfg.SecretKey))
|
||||
mac.Write([]byte(signStr))
|
||||
signature := mac.Sum(nil)
|
||||
|
||||
encodedSign := base64.URLEncoding.EncodeToString(signature)
|
||||
token := fmt.Sprintf("%s:%s", s.cfg.AccessKey, encodedSign)
|
||||
|
||||
return fmt.Sprintf("%s?e=%d&token=%s", baseURL, deadline, token)
|
||||
}
|
||||
|
||||
// Delete 从七牛云删除指定对象。
|
||||
@@ -91,9 +122,17 @@ func (s *StorageService) Delete(ctx context.Context, key string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildURL 根据配置构建完整的 CDN URL。
|
||||
func (s *StorageService) buildURL(key string) string {
|
||||
// buildBaseURL 根据配置构建完整的基础 CDN URL(不含签名参数)。
|
||||
func (s *StorageService) buildBaseURL(key string) string {
|
||||
host := strings.TrimRight(s.cfg.CDNHost, "/")
|
||||
scheme := "http"
|
||||
if s.cfg.UseHTTPS {
|
||||
scheme = "https"
|
||||
}
|
||||
// 如果 host 已经包含 scheme,直接使用;否则添加
|
||||
if !strings.HasPrefix(host, "http://") && !strings.HasPrefix(host, "https://") {
|
||||
host = scheme + "://" + host
|
||||
}
|
||||
segments := strings.Split(key, "/")
|
||||
for i, seg := range segments {
|
||||
segments[i] = url.PathEscape(seg)
|
||||
|
||||
Reference in New Issue
Block a user