package middleware import ( "net/http" "time" "bet24.com/log" "github.com/gin-gonic/gin" "github.com/unrolled/secure" ) // 身份验证(MD5) func CheckValid() gin.HandlerFunc { return func(c *gin.Context) { _ = c.Request.ParseForm() req := c.Request.Form path := c.Request.URL.Path rawPath := c.Request.URL.RawPath log.Debug("%s ==> %s", path, req) start := time.Now() c.Next() //记录耗时信息 if latency := time.Now().Sub(start); latency > 10*time.Second { log.Release("%v %v 访问耗时 %v =====> %+v", path, rawPath, latency, req) } } } // 跨域中间件 // 要在路由组之前全局使用「跨域中间件」, 否则OPTIONS会返回404 func Cors() gin.HandlerFunc { return func(c *gin.Context) { method := c.Request.Method origin := c.Request.Header.Get("Origin") if origin != "" { c.Header("Access-Control-Allow-Origin", origin) c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type") c.Header("Access-Control-Allow-Credentials", "false") c.Set("content-type", "application/json") } if method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) return } c.Next() } } func TlsHandler() gin.HandlerFunc { return func(c *gin.Context) { secureMiddleware := secure.New(secure.Options{ SSLRedirect: true, SSLHost: ":443", }) err := secureMiddleware.Process(c.Writer, c.Request) if err != nil { c.Abort() return } c.Next() } }