添加jwt请求验证功能

This commit is contained in:
2025-08-10 20:34:58 +08:00
parent f41a1a02d6
commit d490ecb405
5 changed files with 16 additions and 1 deletions

10
controllers/test/test.go Normal file
View File

@@ -0,0 +1,10 @@
package test
import (
"github.com/gin-gonic/gin"
"net/http"
)
func Testjwt(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 20002, "msg": "处理请求成功"})
}

View File

@@ -42,7 +42,7 @@ func RedisInit() error {
// 测试连接
_, err = RedisClient.Ping(Ctx).Result()
if err != nil {
return fmt.Errorf("Redis连接失败: %w", err)
panic(fmt.Errorf("Redis连接失败: %w", err))
}
fmt.Println("Redis连接初始化成功")

View File

@@ -5,3 +5,4 @@
-10036 redis缓存失败
-20001 微信登录成功
-20002 请求处理成功

View File

@@ -2,8 +2,10 @@ package router
import (
"github.com/gin-gonic/gin"
"toutoukan/controllers/test"
"toutoukan/controllers/user"
"toutoukan/socket"
"toutoukan/utill"
)
func SetupRouter() *gin.Engine {
@@ -12,6 +14,7 @@ func SetupRouter() *gin.Engine {
apiGroup := r.Group("/user")
{
apiGroup.POST("/login", user.UserLogin)
apiGroup.POST("/test", utill.JWTAuthMiddleware(), test.Testjwt)
}
r.GET("/socket", func(c *gin.Context) {
socket.WebsocketHandler(c)

View File

@@ -84,6 +84,7 @@ func ExtractTokenFromHeader(c *gin.Context) string {
// JWT+Redis验证中间件
func JWTAuthMiddleware() gin.HandlerFunc {
fmt.Println("验证请求")
return func(c *gin.Context) {
tokenString := ExtractTokenFromHeader(c)
if tokenString == "" {