Files
learn-golang/go-gin-middleware/middleware_token.go
2025-12-26 17:56:02 +08:00

70 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"strings"
"github.com/gin-gonic/gin"
)
// Token 认证中间件
func TokenAuth() gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头获取 token
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(401, gin.H{"error": "Missing Authorization header"})
c.Abort()
return
}
// 验证 token 格式Bearer xxx
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
c.JSON(401, gin.H{"error": "Invalid Authorization header"})
c.Abort()
return
}
token := parts[1]
// 验证 token 有效性(简化版,实际应使用 JWT
if !isValidToken(token) {
c.JSON(401, gin.H{"error": "Invalid token"})
c.Abort()
return
}
// 提取用户信息(从 token
userID := extractUserID(token)
c.Set("user_id", userID)
c.Next()
}
}
// 验证 token示例
func isValidToken(token string) bool {
return token == "valid_token_123"
}
// 提取用户ID示例
func extractUserID(token string) string {
return "user123"
}
func main() {
r := gin.Default()
// 需要 token 的路由
r.GET("/profile", TokenAuth(), func(c *gin.Context) {
userID := c.GetString("user_id")
c.JSON(200, gin.H{
"user_id": userID,
"profile": "User profile data",
})
})
r.Run(":9999")
}