Add internal/handler/auth.go

This commit is contained in:
ata
2026-07-10 10:06:31 +00:00
committed by Gitee
parent 6ad29ac05b
commit b493201a17

45
internal/handler/auth.go Normal file
View File

@@ -0,0 +1,45 @@
package handler
import (
"gotest/internal/service"
"github.com/gin-gonic/gin"
)
// AuthHandler 认证处理器
type AuthHandler struct {
authService *service.AuthService
}
// NewAuthHandler 创建认证处理器
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
return &AuthHandler{authService: authService}
}
// Login 登录接口 POST /api/v1/auth/login
func (h *AuthHandler) Login(c *gin.Context) {
var req struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
FailBadRequest(c, "用户名和密码不能为空")
return
}
token, user, err := h.authService.Login(req.Username, req.Password)
if err != nil {
FailUnauthorized(c, err.Error())
return
}
Success(c, gin.H{
"token": token,
"user": gin.H{
"id": user.ID,
"username": user.Username,
"role": user.Role,
"avatar": user.Avatar,
},
})
}