63 lines
1.3 KiB
Go
63 lines
1.3 KiB
Go
package common
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
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: 200,
|
|
Message: "success",
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
// SuccessWithMessage 成功响应(自定义消息)
|
|
func SuccessWithMessage(c *gin.Context, message string, data interface{}) {
|
|
c.JSON(http.StatusOK, Response{
|
|
Code: 200,
|
|
Message: message,
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
// Error 错误响应
|
|
func Error(c *gin.Context, code int, message string) {
|
|
c.JSON(http.StatusOK, Response{
|
|
Code: code,
|
|
Message: message,
|
|
})
|
|
}
|
|
|
|
// ErrorWithData 错误响应(带数据)
|
|
func ErrorWithData(c *gin.Context, code int, message string, data interface{}) {
|
|
c.JSON(http.StatusOK, Response{
|
|
Code: code,
|
|
Message: message,
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
// 常见错误码
|
|
const (
|
|
CodeSuccess = 200
|
|
CodeInvalidParams = 400
|
|
CodeUnauthorized = 401
|
|
CodeForbidden = 403
|
|
CodeNotFound = 404
|
|
CodeInternalError = 500
|
|
CodeServerError = 500 // 服务器错误(别名)
|
|
CodeBindXHSFailed = 1001
|
|
CodeCopyNotAvailable = 1002
|
|
CodeAlreadyClaimed = 1003
|
|
)
|