gin-base/middleware/middleware.go

44 lines
1.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package middleware
import (
"net/http"
"git.magicany.cc/black1552/gin-base/log"
"git.magicany.cc/black1552/gin-base/response"
"github.com/gin-gonic/gin"
)
func ErrorHandler() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
if len(c.Errors) > 0 {
// Step3: Use the last error
laErr := c.Errors.Last().Err
// Step4: Respond with a generic error message
response.Error(c).SetCode(http.StatusInternalServerError).SetMsg(laErr.Error()).End()
}
log.Error("发生panic=》", "path", c.Request.URL.Path, ",method:", c.Request.Method, ",", err)
c.Abort()
}
}()
c.Next()
}
}
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}