package router import ( "demo/data/dao" "fmt" "github.com/gin-gonic/gin" "strings" ) // func Interceptor(InterceptorName string) gin.HandlerFunc { // switch InterceptorName { // case "login": // return LoginInterceptor() // case "log": // return LogInterceptor() // case "authority": // return AuthorityInterceptor() // default: // return func(context *gin.Context) { // fmt.Println("未知拦截器:" + InterceptorName) // } // } // } func Interceptor() gin.HandlerFunc { return func(context *gin.Context) { path := context.FullPath() if path[0:len(Prefix)] == Prefix { path = path[len(Prefix):] } authority := PathRouterMap[path] if authority.AuthorityVerification != "" { Interceptors := strings.Split(authority.AuthorityVerification, ",") for _, v := range Interceptors { switch v { case "log": if !LogInterceptor(context) { return } break case "login": if !LoginInterceptor(context) { return } break case "authority": if !AuthorityInterceptor(context) { return } break default: fmt.Println("未知拦截器:" + v) } } } } } // LoginInterceptor 登录拦截器 func LoginInterceptor(c *gin.Context) bool { id := GetUserIdByToken(c) if id == 0 { fmt.Println("拦截器:用户未登录") //这里终止后续请求访问 c.Abort() return false } return true } // LogInterceptor 日志拦截器 func LogInterceptor(c *gin.Context) bool { keys := c.Keys fmt.Println("==========================日志系统==========================\nkeys:", keys) fmt.Println("路由地址:", c.Request.URL) fmt.Println("路由参数:", c.Request.Form) return true } // AuthorityInterceptor 权限拦截器 func AuthorityInterceptor(c *gin.Context) bool { id := GetUserIdByToken(c) if id == 0 { fmt.Println("拦截器:用户未登录") //这里终止后续请求访问 c.Abort() return false } path := c.FullPath() if path[0:len(Prefix)] == Prefix { path = path[len(Prefix):] } if !dao.CheckAuthorityByUserId(id, PathRouterMap[path].Id) { fmt.Println("拦截器:用户权限不足") c.JSON(200, CreateResultError(500, "权限不足")) //这里终止后续请求访问 c.Abort() return false } return true } // //// LoginInterceptor 登录拦截器 //func LoginInterceptor() gin.HandlerFunc { // return func(c *gin.Context) { // id := GetUserIdByToken(c) // fmt.Println("拦截器", id) // if id == 0 { // fmt.Println("拦截器:用户未登录") // //这里终止后续请求访问 // c.Abort() // return // } // } //} // //// LogInterceptor 日志拦截器 //func LogInterceptor() gin.HandlerFunc { // return func(c *gin.Context) { // fmt.Println("日志系统") // c.Next() // fmt.Println("日志系统666") // } //} // //// AuthorityInterceptor 权限拦截器 //func AuthorityInterceptor() gin.HandlerFunc { // return func(c *gin.Context) { // id := GetUserIdByToken(c) // if id == 0 { // c.Abort() // } // path := c.FullPath() // fmt.Println(path) // // //dao.CheckAuthorityByUserId(id,) // } //}