51 lines
1010 B
Go
51 lines
1010 B
Go
package response
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Response 统一响应结构
|
|
type Response struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
}
|
|
|
|
// Success 成功响应
|
|
func Success(c *gin.Context, data interface{}) {
|
|
c.JSON(http.StatusOK, Response{
|
|
Code: 0,
|
|
Message: "success",
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
// Error 错误响应
|
|
func Error(c *gin.Context, httpStatus int, message string, err error) {
|
|
if err != nil {
|
|
// 在开发环境下返回详细错误信息
|
|
if gin.Mode() == gin.DebugMode {
|
|
c.JSON(httpStatus, Response{
|
|
Code: httpStatus,
|
|
Message: message,
|
|
Data: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
}
|
|
c.JSON(httpStatus, Response{
|
|
Code: httpStatus,
|
|
Message: message,
|
|
})
|
|
}
|
|
|
|
// ErrorWithCode 错误响应(带自定义错误码)
|
|
func ErrorWithCode(c *gin.Context, code int, message string) {
|
|
c.JSON(http.StatusOK, Response{
|
|
Code: code,
|
|
Message: message,
|
|
})
|
|
}
|