## **准备工作** * 根目录下创建 middleware文件夹 并且创建指定的中间件文件 ![](https://img.kancloud.cn/43/92/4392551f75503985d05f50f71e77417d_317x185.png) checkAuth.go ~~~ package middleware import ( "fmt" "github.com/gin-gonic/gin" ) func LoginToken(ctx *gin.Context) { fmt.Println("获取并且解析 前端传来的token") } ~~~ ## **路由中间件** * 注册指定中间件 middleware.LoginToken ~~~ route.GET("/user/list",middleware.LoginToken,api.UserController{}.List) route.POST("/user/insert",middleware.LoginToken,api.UserController{}.Insert) ~~~ ## **全局中间件** ~~~ route.Use(middleware.LoginToken) ~~~ api.go ~~~ package routes import ( "github.com/gin-gonic/gin" "learn_gin/controllers/api" "learn_gin/middleware" ) func Api(r *gin.Engine) { route := r.Group("/api") route.Use(middleware.LoginToken) route.GET("/login", api.Login) route.GET("/user/list",api.UserController{}.List) route.POST("/user/insert",api.UserController{}.Insert) } ~~~ ## **路由分组中间件** ~~~ route.Group("/api",middleware.LoginToken) { route.GET("/user/list",api.UserController{}.List) route.POST("/user/insert",api.UserController{}.Insert) } ~~~ api.go ~~~ package routes import ( "github.com/gin-gonic/gin" "learn_gin/controllers/api" "learn_gin/middleware" ) func Api(r *gin.Engine) { route := r.Group("/api") route.GET("/login", api.Login) route.Group("/api",middleware.LoginToken) { route.GET("/user/list",api.UserController{}.List) route.POST("/user/insert",api.UserController{}.Insert) } } ~~~ ## **拓展** * 配置多个中间 `c.Next` ![](https://img.kancloud.cn/76/c1/76c1047034a2e2202ff70160d422860d_639x387.png) ![](https://img.kancloud.cn/e5/7a/e57a7abe8164030a4972492a2e20872d_687x137.png) ![](https://img.kancloud.cn/d3/62/d3624f351c3f69236bf68a64668e207a_682x132.png) `c.Abort`