Enhance API and error handling for video services
- Updated .gitignore to exclude cache files. - Refactored main.go to streamline route registration and improve code organization. - Added detailed comments in auth_handler.go, video_handler.go, and service files for better clarity on request handling and service logic. - Improved error messages in video_handler.go to provide clearer feedback to users in Chinese. - Introduced context handling in service methods to manage request timeouts effectively.
This commit is contained in:
@@ -31,3 +31,4 @@ go.work
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
.cache/*
|
||||
|
||||
+9
-16
@@ -2,31 +2,35 @@ package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/config"
|
||||
"wx_service/internal/database"
|
||||
"wx_service/internal/handler"
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
"wx_service/internal/routes"
|
||||
"wx_service/internal/service"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 1) 加载配置(通常来自环境变量 / .env)
|
||||
config.LoadConfig()
|
||||
|
||||
// 2) 初始化数据库连接
|
||||
if err := database.InitDB(); err != nil {
|
||||
log.Fatalf("init database failed: %v", err)
|
||||
}
|
||||
// 3) 自动建表/迁移(开发阶段很方便;生产环境可改为手动迁移)
|
||||
if err := database.AutoMigrate(&model.MiniProgram{}, &model.User{}, &model.VideoParseLog{}, &model.VideoParseUnlock{}); err != nil {
|
||||
log.Fatalf("auto migrate failed: %v", err)
|
||||
}
|
||||
|
||||
// 4) 初始化 HTTP 框架(Gin)
|
||||
gin.SetMode(config.AppConfig.Server.Mode)
|
||||
router := gin.Default()
|
||||
|
||||
// 5) 依赖注入:先创建 service,再创建 handler(handler 只关心 HTTP 输入/输出)
|
||||
miniProgramService := service.NewMiniProgramService(database.DB)
|
||||
authService := service.NewAuthService(database.DB, miniProgramService)
|
||||
authHandler := handler.NewAuthHandler(authService)
|
||||
@@ -36,21 +40,10 @@ func main() {
|
||||
}
|
||||
videoHandler := handler.NewVideoHandler(videoService)
|
||||
|
||||
api := router.Group("/api/v1")
|
||||
{
|
||||
api.POST("/auth/login", authHandler.LoginWithWeChat)
|
||||
protected := api.Group("")
|
||||
protected.Use(middleware.AuthMiddleware(database.DB))
|
||||
{
|
||||
protected.POST("/video/remove_watermark", videoHandler.RemoveWatermark)
|
||||
protected.POST("/video/remove_watermark/unlock", videoHandler.UnlockQuota)
|
||||
}
|
||||
}
|
||||
|
||||
router.GET("/healthz", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
})
|
||||
// 6) 注册路由:把 URL 映射到 handler
|
||||
routes.Register(router, database.DB, authHandler, videoHandler)
|
||||
|
||||
// 7) 启动监听端口
|
||||
addr := ":" + config.AppConfig.Server.Port
|
||||
if err := router.Run(addr); err != nil {
|
||||
log.Fatalf("server stopped: %v", err)
|
||||
|
||||
@@ -11,6 +11,10 @@ import (
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
// handler 层通常只做“协议转换”:
|
||||
// - 把 HTTP 请求(JSON/header 等)解析成结构体
|
||||
// - 调用 service 完成业务逻辑
|
||||
// - 把结果/错误转换成统一的 JSON 响应
|
||||
authService *service.AuthService
|
||||
}
|
||||
|
||||
@@ -21,21 +25,30 @@ func NewAuthHandler(authService *service.AuthService) *AuthHandler {
|
||||
}
|
||||
|
||||
type weChatLoginRequest struct {
|
||||
// binding:"required" 是 Gin 的校验标签:字段缺失或为空会导致 ShouldBindJSON 返回错误
|
||||
MiniProgramID uint `json:"mini_program_id" binding:"required"`
|
||||
Code string `json:"code" binding:"required"`
|
||||
NickName string `json:"nickname"`
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
Gender *int `json:"gender"`
|
||||
Phone string `json:"phone"`
|
||||
// 使用 *int 可以区分:
|
||||
// - nil:前端没传 gender
|
||||
// - 非 nil:前端传了具体值(即使是 0)
|
||||
Gender *int `json:"gender"`
|
||||
Phone string `json:"phone"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) LoginWithWeChat(c *gin.Context) {
|
||||
// gin.Context 是每个请求的上下文对象:
|
||||
// - c.Request.Context() 是标准库 context,用于把超时/取消信号传递到 DB/HTTP 调用
|
||||
// - c.JSON(...) 用于写 JSON 响应
|
||||
var req weChatLoginRequest
|
||||
// ShouldBindJSON 会从请求体 JSON 反序列化到结构体,并根据 binding 标签做基础校验
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid request payload"))
|
||||
return
|
||||
}
|
||||
|
||||
// 业务逻辑下沉到 service:这样 handler 更薄、更容易测试
|
||||
result, err := h.authService.LoginWithCode(c.Request.Context(), service.LoginRequest{
|
||||
MiniProgramID: req.MiniProgramID,
|
||||
Code: req.Code,
|
||||
|
||||
@@ -28,13 +28,13 @@ type removeWatermarkRequest struct {
|
||||
func (h *VideoHandler) RemoveWatermark(c *gin.Context) {
|
||||
var req removeWatermarkRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid request payload"))
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
|
||||
user, ok := getCurrentUser(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "unauthorized"))
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -42,21 +42,21 @@ func (h *VideoHandler) RemoveWatermark(c *gin.Context) {
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrURLNotFound):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "content must contain a valid url"))
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请检查分享链接是否正确"))
|
||||
return
|
||||
case errors.Is(err, service.ErrDailyQuotaExceeded):
|
||||
c.JSON(http.StatusForbidden, model.Error(http.StatusForbidden, err.Error()))
|
||||
c.JSON(http.StatusForbidden, model.Error(http.StatusForbidden, "今日免费次数已用完,观看广告后今天可无限制使用"))
|
||||
return
|
||||
case errors.Is(err, service.ErrShortVideoAPIKey):
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "short video api key missing"))
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "服务暂不可用,请联系管理员"))
|
||||
return
|
||||
default:
|
||||
var thirdPartyErr *service.ThirdPartyError
|
||||
if errors.As(err, &thirdPartyErr) {
|
||||
c.JSON(http.StatusBadGateway, model.Error(http.StatusBadGateway, thirdPartyErr.Error()))
|
||||
c.JSON(http.StatusBadGateway, model.Error(http.StatusBadGateway, "解析服务异常,请稍后重试"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "remove watermark failed"))
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "去水印失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -71,12 +71,12 @@ func (h *VideoHandler) RemoveWatermark(c *gin.Context) {
|
||||
func (h *VideoHandler) UnlockQuota(c *gin.Context) {
|
||||
user, ok := getCurrentUser(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "unauthorized"))
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.videoService.UnlockForToday(c.Request.Context(), user); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "unlock failed"))
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "解锁失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ import (
|
||||
const ContextCurrentUserKey = "currentUser"
|
||||
|
||||
func AuthMiddleware(db *gorm.DB) gin.HandlerFunc {
|
||||
// AuthMiddleware 是一个 Gin 中间件:
|
||||
// - 从 Authorization: Bearer <token> 里取 token
|
||||
// - 用 token(这里是 session_key)查用户
|
||||
// - 查到后放进 gin.Context,供后面的 handler 使用
|
||||
return func(c *gin.Context) {
|
||||
token := extractToken(c.GetHeader("Authorization"))
|
||||
if token == "" {
|
||||
@@ -36,6 +40,7 @@ func AuthMiddleware(db *gorm.DB) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
func extractToken(authHeader string) string {
|
||||
// 常见格式:Authorization: Bearer <token>
|
||||
if authHeader == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"wx_service/internal/handler"
|
||||
"wx_service/internal/middleware"
|
||||
)
|
||||
|
||||
func Register(router *gin.Engine, db *gorm.DB, authHandler *handler.AuthHandler, videoHandler *handler.VideoHandler) {
|
||||
// Register 用来集中注册所有 HTTP 路由,便于工程结构更清晰:
|
||||
// - main 只负责初始化(配置/DB/依赖注入)
|
||||
// - routes 只负责把 URL 映射到 handler
|
||||
api := router.Group("/api/v1")
|
||||
{
|
||||
// 登录接口:用微信 code 换取/创建用户并返回 session_key(作为后续 Bearer Token)
|
||||
api.POST("/auth/login", authHandler.LoginWithWeChat)
|
||||
|
||||
// 需要登录的接口组:统一挂载鉴权中间件
|
||||
protected := api.Group("")
|
||||
protected.Use(middleware.AuthMiddleware(db))
|
||||
{
|
||||
protected.POST("/video/remove_watermark", videoHandler.RemoveWatermark)
|
||||
protected.POST("/video/remove_watermark/unlock", videoHandler.UnlockQuota)
|
||||
}
|
||||
}
|
||||
|
||||
// 健康检查:用于容器/负载均衡探活
|
||||
router.GET("/healthz", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
})
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
)
|
||||
|
||||
type MiniProgramService struct {
|
||||
// service 层负责“业务能力”,通常会依赖数据库/第三方客户端等基础设施。
|
||||
// 这里通过结构体字段持有 db(依赖注入),而不是在方法里自己创建连接。
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
@@ -17,6 +19,7 @@ func NewMiniProgramService(db *gorm.DB) *MiniProgramService {
|
||||
}
|
||||
|
||||
func (s *MiniProgramService) GetByID(ctx context.Context, id uint) (*model.MiniProgram, error) {
|
||||
// WithContext(ctx) 能把请求的超时/取消信号传递给数据库层,避免慢请求一直挂着。
|
||||
var mp model.MiniProgram
|
||||
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&mp).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
const removeWatermarkEndpoint = "https://api.23bt.cn/api/d1w/index"
|
||||
|
||||
var (
|
||||
// 从用户输入的文本里“抓取 URL”的简单正则(找到第一个 http/https 链接)
|
||||
urlPattern = regexp.MustCompile(`https?://[^\s]+`)
|
||||
ErrURLNotFound = errors.New("no valid url found in content")
|
||||
ErrShortVideoAPIKey = errors.New("short video api key is not configured")
|
||||
@@ -28,12 +29,18 @@ var (
|
||||
)
|
||||
|
||||
type VideoService struct {
|
||||
// VideoService 封装“去水印”相关业务:
|
||||
// - 限额(每天免费次数)
|
||||
// - 调用第三方解析接口
|
||||
// - 记录解析日志(便于排查问题/统计)
|
||||
db *gorm.DB
|
||||
cfg config.ShortVideoConfig
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type RemoveWatermarkResult struct {
|
||||
// json.RawMessage 表示“原始 JSON 字节”,不强制把第三方返回结构定义成 Go struct。
|
||||
// 对接不稳定/字段多的第三方接口时,这种做法更灵活。
|
||||
Provider string `json:"provider"`
|
||||
Raw json.RawMessage `json:"raw"`
|
||||
FreeQuotaUsed bool `json:"free_quota_used"`
|
||||
@@ -51,6 +58,7 @@ func (e *ThirdPartyError) Error() string {
|
||||
func NewVideoService(db *gorm.DB, cfg config.ShortVideoConfig) (*VideoService, error) {
|
||||
timeout := cfg.RequestTimeout
|
||||
if timeout <= 0 {
|
||||
// 不配置就给一个默认超时,避免请求卡住占用 goroutine
|
||||
timeout = 5 * time.Second
|
||||
}
|
||||
|
||||
@@ -66,6 +74,11 @@ func NewVideoService(db *gorm.DB, cfg config.ShortVideoConfig) (*VideoService, e
|
||||
}
|
||||
|
||||
func (s *VideoService) RemoveWatermark(ctx context.Context, user *model.User, content string) (*RemoveWatermarkResult, error) {
|
||||
// RemoveWatermark 的整体流程:
|
||||
// 1) 从 content 里提取链接
|
||||
// 2) 检查每日免费额度(或是否已解锁)
|
||||
// 3) 调用第三方接口解析
|
||||
// 4) 写入解析日志(无论成功/失败都记一条,方便定位问题)
|
||||
link, err := extractFirstURL(content)
|
||||
if err != nil {
|
||||
return nil, ErrURLNotFound
|
||||
@@ -118,6 +131,7 @@ func (s *VideoService) RemoveWatermark(ctx context.Context, user *model.User, co
|
||||
}
|
||||
|
||||
func (s *VideoService) UnlockForToday(ctx context.Context, user *model.User) error {
|
||||
// “看广告解锁”的实现方式:在当天写一条 unlock 记录即可(存在则更新时间戳)
|
||||
startOfDay, _ := dayRange(time.Now())
|
||||
|
||||
var unlock model.VideoParseUnlock
|
||||
@@ -145,6 +159,9 @@ func (s *VideoService) UnlockForToday(ctx context.Context, user *model.User) err
|
||||
}
|
||||
|
||||
func (s *VideoService) ensureQuota(ctx context.Context, user *model.User) (bool, error) {
|
||||
// ensureQuota 返回值 freeQuotaUsed 的含义:
|
||||
// - true:这次调用会消耗一次“免费额度”
|
||||
// - false:不消耗(例如今日已解锁或未启用限额)
|
||||
if s.cfg.FreeDailyQuota <= 0 {
|
||||
return false, nil
|
||||
}
|
||||
@@ -208,6 +225,7 @@ func (s *VideoService) callThirdParty(ctx context.Context, link string) (int, []
|
||||
}
|
||||
|
||||
func extractFirstURL(content string) (string, error) {
|
||||
// 从文本里提取第一个 URL,并做简单 trim,把末尾可能粘上的标点去掉。
|
||||
if content == "" {
|
||||
return "", ErrURLNotFound
|
||||
}
|
||||
@@ -219,6 +237,8 @@ func extractFirstURL(content string) (string, error) {
|
||||
}
|
||||
|
||||
func dayRange(ts time.Time) (time.Time, time.Time) {
|
||||
// 计算“当天的起止时间”:[00:00, 次日00:00)
|
||||
// 用本地时区 loc,避免跨时区导致的日期偏移。
|
||||
loc := ts.Location()
|
||||
start := time.Date(ts.Year(), ts.Month(), ts.Day(), 0, 0, 0, 0, loc)
|
||||
end := start.Add(24 * time.Hour)
|
||||
@@ -226,6 +246,7 @@ func dayRange(ts time.Time) (time.Time, time.Time) {
|
||||
}
|
||||
|
||||
func truncateString(input string, max int) string {
|
||||
// 截断字符串,避免把第三方错误响应原样写入导致日志过大
|
||||
if len(input) <= max {
|
||||
return input
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user