package jwt import ( //"strings" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "../../pkg/e" "../../pkg/util" jwtGet "../../pkg/util" ) func JWT() gin.HandlerFunc { return func(c *gin.Context) { var code int var data interface{} code = e.SUCCESS //Authorization := c.GetHeader("Authorization") //token := strings.Split(Authorization, " ") Authorization := c.GetHeader("token") token := Authorization if Authorization == "" { code = e.INVALID_PARAMS } else { //_, err := util.ParseToken(token[1]) _, err := util.ParseToken(token) if err != nil { switch err.(*jwt.ValidationError).Errors { case jwt.ValidationErrorExpired: code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT default: code = e.ERROR_AUTH_CHECK_TOKEN_FAIL } } } if code != e.SUCCESS { c.JSON(e.SUCCESS, gin.H{ "code": code, "msg": "登录超时", "data": data, }) c.Abort() return } t, _ := jwt.Parse(token, func(*jwt.Token) (interface{}, error) { return jwtGet.JwtSecret, nil }) c.Set("jwt_username",jwtGet.GetIdFromClaims("username", t.Claims)) c.Next() } }