Files
nl-blogs/server/utils/response.go
2026-01-16 10:19:30 +08:00

56 lines
1.1 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 错误响应 (默认 Code 400)
func Error(c *gin.Context, code int, msg string) {
httpStatus := http.StatusBadRequest
if code == 500 {
httpStatus = http.StatusInternalServerError
}
c.JSON(httpStatus, Response{
Code: code,
Message: msg,
Result: nil,
})
}
// ServerError 服务器错误 (Code 500)
func ServerError(c *gin.Context, err error) {
c.JSON(http.StatusInternalServerError, Response{
Code: 500,
Message: err.Error(),
Result: nil,
})
}