api.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "go_zh/model"
  5. "net/http"
  6. )
  7. // 不需要token验证的路由白名单
  8. var whiteList = []string{
  9. "/api/auth/login",
  10. }
  11. func ApiMiddleware() gin.HandlerFunc {
  12. return func(c *gin.Context) {
  13. // 检查当前路径是否在白名单中
  14. if isPathInWhiteList(c.Request.URL.Path) {
  15. c.Next()
  16. return
  17. }
  18. // 从Header或Query中获取token
  19. token := c.GetHeader("Authorization")
  20. if token == "" {
  21. token = c.Query("token")
  22. }
  23. if token == "" {
  24. c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
  25. "code": 401,
  26. "message": "缺少认证信息",
  27. "data": nil,
  28. })
  29. return
  30. }
  31. //根据token获取用户信息
  32. memberModel := model.XMember{}
  33. member, err := memberModel.GetMemberByToken(token)
  34. if err != nil {
  35. c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
  36. "code": 401,
  37. "message": "认证信息已过期",
  38. "data": nil,
  39. })
  40. }
  41. c.Set("mId", member.ID)
  42. c.Next()
  43. }
  44. }
  45. // isPathInWhiteList 检查路径是否在白名单中
  46. func isPathInWhiteList(path string) bool {
  47. for _, whitePath := range whiteList {
  48. // 精确匹配(用于匹配路径前缀)
  49. if path == whitePath {
  50. return true
  51. }
  52. }
  53. return false
  54. }