git 地址
https://github.com/hailin86/ginApi/tree/middleware
中间件有全局中间件 和 局部中间件 ,下面笔者写了三个中间件 分别是:
1.解决跨域中间件 (全局),所有接口都需要走该中间件
2.校验请求合法性的中间件 (局部),比如 判断该请求的appKey 是不是服务端下发的
3.校验用户是否登录的中间件 (局部),比如某些接口只有登录后才能查看
在app目录下新增 middleware 文件夹,然后该文件夹下分别新建 cors.go,appIns.go,auth.go
//解决跨域请求中间件 func Cors() gin.HandlerFunc { return func(c *gin.Context) { method := c.Request.Method c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,GINAPPKEY,GINTOKEN,GINTIME,GINSIGN") c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS") 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") if method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) } //c.Next() } }
//校验appInstance 中间件
func CheckAppInstance() gin.HandlerFunc { return func(c *gin.Context) { header := c.Request.Header appKey := header.Get("Ginappkey") if appKey =="" { c.JSON(http.StatusOK,gin.H{ "code":1,"msg":"appKey not exists","data":nil}) c.Abort() return } //获取到appKey 时间戳 等做一下校验 if appKey != "1000000" { c.JSON(http.StatusOK,gin.H{"code":1,"msg":"appKey not exists1","data":nil}) c.Abort() return } //做一些 sign签名与 timestamp 时间戳的校验 //... //c.Next() } }
//校验用户登录中间件
func CheckUserAuth() gin.HandlerFunc { return func(c *gin.Context) { // ginToken := c.Request.Header.Get("GINTOKEN") if ginToken == "" { common.Failed(c,"token 不存在",1,nil) //c.JSON(http.StatusOK,gin.H{"code":1,"msg":"","data":nil}) c.Abort() return } //此处可以配合jwt解析token userId,_ := strconv.Atoi(ginToken) c.Set("userId",userId) //c.Next() // 后续的处理函数可以用过c.Get("userId")来获取当前请求的用户信息 } }
在初始化路由 ,注释掉 use(middleware.Cors())
ajax 模拟请求
可以看到返回结果显示跨域
放开 全局中间件
再次请求
可以看到 跨域中间件生效。
同理 局部中间件可以针对路由组去做一些过滤处理 比如
testcontroller 做一下测试 不走 2 3 中间件
productcontroller 下的业务 不走3 中间件 只需走 1 2
ordercontroller 需要登录才能查看 ,需要走 1 2 3 中间件
比如请求 product 下的接口
会提示 appKey 不存在所有证实中间件2 生效
带上appKey 以后 继续请求 order 下的接口
会提示 token不存在 ,说明中间件3 生效