51 lines
1.0 KiB
Go
51 lines
1.0 KiB
Go
package utils
|
||
|
||
import (
|
||
"net/http"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// Response 统一响应结构
|
||
type Response struct {
|
||
Code int `json:"code"`
|
||
Message string `json:"message"`
|
||
Result interface{} `json:"result"`
|
||
}
|
||
|
||
// Success 成功响应 (Code 200)
|
||
func Success(c *gin.Context, result interface{}) {
|
||
c.JSON(http.StatusOK, Response{
|
||
Code: 200,
|
||
Message: "Success",
|
||
Result: result,
|
||
})
|
||
}
|
||
|
||
// SuccessWithMsg 自定义消息成功响应
|
||
func SuccessWithMsg(c *gin.Context, msg string, result interface{}) {
|
||
c.JSON(http.StatusOK, Response{
|
||
Code: 200,
|
||
Message: msg,
|
||
Result: result,
|
||
})
|
||
}
|
||
|
||
// Error 错误响应,HTTP 状态恒为 200,通过 code 区分业务状态
|
||
func Error(c *gin.Context, code int, msg string) {
|
||
c.JSON(http.StatusOK, Response{
|
||
Code: code,
|
||
Message: msg,
|
||
Result: nil,
|
||
})
|
||
}
|
||
|
||
// ServerError 服务器错误 (Code 500)
|
||
func ServerError(c *gin.Context, err error) {
|
||
c.JSON(http.StatusOK, Response{
|
||
Code: 500,
|
||
Message: err.Error(),
|
||
Result: nil,
|
||
})
|
||
}
|