Integrate Qiniu upload service and update configuration
- Added Qiniu configuration options to .env.example and config.go for file uploads. - Refactored main.go to include new Qiniu service and upload handler. - Updated route registration to accommodate the new upload handler. - Enhanced documentation to include references for Qiniu upload functionality. - Removed legacy authentication handler and services to streamline the codebase.
This commit is contained in:
@@ -6,8 +6,8 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/common/auth/service"
|
||||
"wx_service/internal/model"
|
||||
"wx_service/internal/service"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
@@ -0,0 +1,50 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/common/service"
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
type UploadHandler struct {
|
||||
qiniuService *service.QiniuService
|
||||
}
|
||||
|
||||
func NewUploadHandler(qiniuService *service.QiniuService) *UploadHandler {
|
||||
return &UploadHandler{qiniuService: qiniuService}
|
||||
}
|
||||
|
||||
type qiniuTokenRequest struct {
|
||||
// filename 用于保留文件后缀(可选),例如:"a.png"、"video.mp4"
|
||||
Filename string `json:"filename"`
|
||||
}
|
||||
|
||||
// QiniuToken 返回七牛直传所需的 token/key/upload_url 等信息。
|
||||
// 建议放在鉴权后:用当前登录用户生成 key,避免前端写入任意路径。
|
||||
func (h *UploadHandler) QiniuToken(c *gin.Context) {
|
||||
user, ok := middleware.CurrentUser(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
||||
return
|
||||
}
|
||||
|
||||
var req qiniuTokenRequest
|
||||
_ = c.ShouldBindJSON(&req) // filename 可选,解析失败也不影响生成 token
|
||||
|
||||
token, err := h.qiniuService.CreateUploadToken(user.MiniProgramID, user.ID, req.Filename)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrQiniuNotConfigured) {
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置七牛上传服务,请联系管理员"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取上传凭证失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(token))
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"wx_service/config"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrQiniuNotConfigured = errors.New("qiniu is not configured")
|
||||
)
|
||||
|
||||
type QiniuService struct {
|
||||
cfg config.QiniuConfig
|
||||
}
|
||||
|
||||
func NewQiniuService(cfg config.QiniuConfig) *QiniuService {
|
||||
return &QiniuService{cfg: cfg}
|
||||
}
|
||||
|
||||
type QiniuUploadToken struct {
|
||||
Token string `json:"token"`
|
||||
Key string `json:"key"`
|
||||
UploadURL string `json:"upload_url"`
|
||||
ExpireAt int64 `json:"expire"`
|
||||
CDNDomain string `json:"cdn_domain"`
|
||||
}
|
||||
|
||||
var extPattern = regexp.MustCompile(`^\.[a-z0-9]{1,10}$`)
|
||||
|
||||
func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filename string) (QiniuUploadToken, error) {
|
||||
if s.cfg.AccessKey == "" || s.cfg.SecretKey == "" || s.cfg.Bucket == "" {
|
||||
return QiniuUploadToken{}, ErrQiniuNotConfigured
|
||||
}
|
||||
|
||||
expireSeconds := s.cfg.TokenExpireSeconds
|
||||
if expireSeconds <= 0 {
|
||||
expireSeconds = 300
|
||||
}
|
||||
expireAt := time.Now().Add(time.Duration(expireSeconds) * time.Second).Unix()
|
||||
|
||||
ext := strings.ToLower(path.Ext(filename))
|
||||
if !extPattern.MatchString(ext) {
|
||||
ext = ""
|
||||
}
|
||||
|
||||
randomHex, err := randomHex(16)
|
||||
if err != nil {
|
||||
return QiniuUploadToken{}, fmt.Errorf("generate random key: %w", err)
|
||||
}
|
||||
|
||||
// 统一由后端生成 key,避免前端随意写入任意路径。
|
||||
// 这里按“业务前缀/小程序/用户/日期/随机名”组织,便于后期排查与管理。
|
||||
keyPrefix := strings.Trim(s.cfg.KeyPrefix, "/")
|
||||
key := fmt.Sprintf("%s/mp_%d/user_%d/%s/%s%s",
|
||||
keyPrefix,
|
||||
miniProgramID,
|
||||
userID,
|
||||
time.Now().Format("20060102"),
|
||||
randomHex,
|
||||
ext,
|
||||
)
|
||||
|
||||
putPolicy := map[string]interface{}{
|
||||
// scope = "<bucket>:<key>" 表示只允许写入指定 key(更安全)
|
||||
"scope": fmt.Sprintf("%s:%s", s.cfg.Bucket, key),
|
||||
"deadline": expireAt,
|
||||
// 上传完成后返回给前端的 JSON(七牛会做变量替换)
|
||||
"returnBody": `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"mimeType":"$(mimeType)"}`,
|
||||
}
|
||||
|
||||
policyJSON, err := json.Marshal(putPolicy)
|
||||
if err != nil {
|
||||
return QiniuUploadToken{}, fmt.Errorf("marshal put policy: %w", err)
|
||||
}
|
||||
|
||||
encodedPolicy := urlSafeBase64NoPad(policyJSON)
|
||||
sign := hmacSHA1([]byte(s.cfg.SecretKey), []byte(encodedPolicy))
|
||||
encodedSign := urlSafeBase64NoPad(sign)
|
||||
|
||||
token := fmt.Sprintf("%s:%s:%s", s.cfg.AccessKey, encodedSign, encodedPolicy)
|
||||
|
||||
return QiniuUploadToken{
|
||||
Token: token,
|
||||
Key: key,
|
||||
UploadURL: s.cfg.UploadURL,
|
||||
ExpireAt: expireAt,
|
||||
CDNDomain: s.cfg.CDNDomain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func hmacSHA1(secret []byte, data []byte) []byte {
|
||||
mac := hmac.New(sha1.New, secret)
|
||||
mac.Write(data)
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
|
||||
func urlSafeBase64NoPad(data []byte) string {
|
||||
return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(data)
|
||||
}
|
||||
|
||||
func randomHex(nBytes int) (string, error) {
|
||||
if nBytes <= 0 {
|
||||
return "", fmt.Errorf("invalid random bytes length")
|
||||
}
|
||||
buf := make([]byte, nBytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
commonhandler "wx_service/internal/common/handler"
|
||||
)
|
||||
|
||||
func registerCommonRoutes(protected *gin.RouterGroup, uploadHandler *commonhandler.UploadHandler) {
|
||||
// 公共接口(所有小程序共用)
|
||||
common := protected.Group("/common")
|
||||
{
|
||||
// 七牛直传凭证:前端先拿 token,再直传文件到七牛 upload_url
|
||||
common.POST("/upload/qiniu/token", uploadHandler.QiniuToken)
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,8 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"wx_service/internal/handler"
|
||||
authhandler "wx_service/internal/common/auth/handler"
|
||||
commonhandler "wx_service/internal/common/handler"
|
||||
"wx_service/internal/middleware"
|
||||
rmhandler "wx_service/internal/remove_watermark/handler"
|
||||
smokehandler "wx_service/internal/smoke/handler"
|
||||
@@ -15,9 +16,10 @@ import (
|
||||
func Register(
|
||||
router *gin.Engine,
|
||||
db *gorm.DB,
|
||||
authHandler *handler.AuthHandler,
|
||||
authHandler *authhandler.AuthHandler,
|
||||
videoHandler *rmhandler.VideoHandler,
|
||||
smokeHandler *smokehandler.SmokeHandler,
|
||||
uploadHandler *commonhandler.UploadHandler,
|
||||
) {
|
||||
// Register 用来集中注册所有 HTTP 路由,便于工程结构更清晰:
|
||||
// - main 只负责初始化(配置/DB/依赖注入)
|
||||
@@ -31,6 +33,7 @@ func Register(
|
||||
protected := api.Group("")
|
||||
protected.Use(middleware.AuthMiddleware(db))
|
||||
{
|
||||
registerCommonRoutes(protected, uploadHandler)
|
||||
registerRemoveWatermarkRoutes(protected, videoHandler)
|
||||
registerSmokeRoutes(protected, smokeHandler)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user