| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- package middleware
- import (
- "github.com/gin-gonic/gin"
- "go_zh/model"
- "net/http"
- )
- // 不需要token验证的路由白名单
- var whiteList = []string{
- "/api/auth/login",
- }
- func ApiMiddleware() gin.HandlerFunc {
- return func(c *gin.Context) {
- // 检查当前路径是否在白名单中
- if isPathInWhiteList(c.Request.URL.Path) {
- c.Next()
- return
- }
- // 从Header或Query中获取token
- token := c.GetHeader("Authorization")
- if token == "" {
- token = c.Query("token")
- }
- if token == "" {
- c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
- "code": 401,
- "message": "缺少认证信息",
- "data": nil,
- })
- return
- }
- //根据token获取用户信息
- memberModel := model.XMember{}
- member, err := memberModel.GetMemberByToken(token)
- if err != nil {
- c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
- "code": 401,
- "message": "认证信息已过期",
- "data": nil,
- })
- }
- c.Set("mId", member.ID)
- c.Next()
- }
- }
- // isPathInWhiteList 检查路径是否在白名单中
- func isPathInWhiteList(path string) bool {
- for _, whitePath := range whiteList {
- // 精确匹配(用于匹配路径前缀)
- if path == whitePath {
- return true
- }
- }
- return false
- }
|