Files
2022-01-17 09:57:57 +08:00

98 lines
2.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package router
import (
"SciencesServer/serve/logger"
"context"
"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("Recoverrequest【%s】 error【%v】\n", c.Request.URL, err)
c.JSON(http.StatusInternalServerError, gin.H{
"message": "Internal Server Error",
})
c.Abort()
return
}
}()
c.Next()
}
}