55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-contrib/cors"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// CORS 跨域配置
|
|
func CORS() gin.HandlerFunc {
|
|
return cors.New(cors.Config{
|
|
AllowOrigins: []string{"*"},
|
|
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
|
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
|
|
AllowCredentials: true,
|
|
})
|
|
}
|
|
|
|
// ErrorHandler 统一错误处理中间件
|
|
func ErrorHandler() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Next()
|
|
|
|
if len(c.Errors) > 0 {
|
|
c.JSON(http.StatusInternalServerError, gin.H{
|
|
"code": 500,
|
|
"message": c.Errors.Last().Error(),
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
// ApiResponse 统一响应格式
|
|
type ApiResponse struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
}
|
|
|
|
func Success(c *gin.Context, data interface{}) {
|
|
c.JSON(http.StatusOK, ApiResponse{
|
|
Code: 0,
|
|
Message: "ok",
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
func Error(c *gin.Context, httpStatus int, code int, message string) {
|
|
c.AbortWithStatusJSON(httpStatus, ApiResponse{
|
|
Code: code,
|
|
Message: message,
|
|
})
|
|
}
|