EasyGoAdmin_Gin_EleVue-2 发表于 2023-07-13 | 更新于 2024-09-02 | 分类于 Gin 本文字数: 12k | 阅读时长 ≈ 10 分钟 思考并回答以下问题: middleware app/middleware/checklogin.go 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950/** * 登录验证中间件 * @File : checkauth */package middlewareimport ( "easygoadmin/utils" "easygoadmin/utils/common" "easygoadmin/utils/gstr" "fmt" "github.com/gin-gonic/gin" "net/http" "time")func CheckLogin() gin.HandlerFunc { return func(ctx *gin.Context) { fmt.Println("登录验证中间件") // 放行设置 urlItem := []string{"/captcha", "/login"} if !utils.InStringArray(ctx.Request.RequestURI, urlItem) { // 从请求头中获取Token token := ctx.GetHeader("Authorization") // 字符串替换 token = gstr.Replace(token, "Bearer ", "") claim, err := utils.ParseToken(token) if err != nil { fmt.Println("解析token出现错误:", err) ctx.JSON(http.StatusOK, common.JsonResult{ Code: 401, Msg: "Token已过期", }) ctx.Abort() return } else if time.Now().Unix() > claim.ExpiresAt { fmt.Println("时间超时") ctx.JSON(http.StatusOK, common.JsonResult{ Code: 401, Msg: "时间超时", }) ctx.Abort() return } } // 前置中间件 ctx.Next() }} app/middleware/cros.go 123456789101112131415161718192021222324252627282930313233343536373839404142/** * 跨域处理中间件 * @File : cros */package middlewareimport ( "github.com/gin-gonic/gin" "net/http")// 处理跨域请求,支持options访问func Cros() gin.HandlerFunc { return func(c *gin.Context) { origin := c.GetHeader("Origin") if len(origin) == 0 { c.Next() return } // 同源直接过 host := c.GetHeader("Host") if origin == "http://"+host || origin == "https://"+host { c.Next() return } c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token") c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE") c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type") c.Header("Access-Control-Allow-Credentials", "true") // OPTIONS 过 method := c.Request.Method if method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) c.Abort() } c.Next() }}