package router import ( "SciencesServer/config" "SciencesServer/serve/logger" "context" "fmt" "net/http" "time" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" ) 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", "access-control-allow-origin, access-control-allow-headers, application/octet-stream") 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) return } c.Next() } } // NoMethodHandler 未找到请求方法的处理函数 func NoMethodHandler() gin.HandlerFunc { return func(c *gin.Context) { c.JSON(http.StatusMethodNotAllowed, gin.H{ "message": "未找到请求路由的处理函数", }) c.Abort() return } } // NoRouteHandler 未找到请求路由的处理函数 func NoRouteHandler() gin.HandlerFunc { return func(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{ "message": "未找到请求路由的处理函数", }) c.Abort() return } } func LoggerHandle(log string, leastDay uint) gin.HandlerFunc { _logger := logger.NewLogger().Init(&logger.Option{File: log, LeastDay: leastDay, Level: "debug", IsStdout: false}).Logger return func(c *gin.Context) { _logger.Log(logrus.InfoLevel, map[string]interface{}{ "Status": c.Writer.Status(), "IP": c.ClientIP(), "Method": c.Request.Method, "Url": c.Request.RequestURI, }) } } // TimeoutHandle 超时处理 func TimeoutHandle(timeout time.Duration) gin.HandlerFunc { return func(c *gin.Context) { ctx, cancel := context.WithTimeout(c.Request.Context(), timeout) defer func() { if ctx.Err() == context.DeadlineExceeded { c.Writer.WriteHeader(http.StatusGatewayTimeout) c.Abort() } cancel() }() c.Request = c.Request.WithContext(ctx) c.Next() } } // RecoveryHandler 崩溃恢复中间件 func RecoveryHandler() gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { fmt.Printf("Recover:request【%s】 error:【%v】\n", c.Request.URL, err) c.JSON(http.StatusInternalServerError, gin.H{ "message": "Internal Server Error!", }) c.Abort() return } }() c.Next() } } // ContentAnalysisHandler 消息体解析 func ContentAnalysisHandler() gin.HandlerFunc { return func(c *gin.Context) { url := c.Request.URL var data string value, has := config.SystemConfig[url.String()] if has { data = value.(string) } c.Set(config.ContentForLocal, data) } }