Files
nl-blogs/server/utils/response.go

51 lines
1.0 KiB
Go
Raw Normal View History

2026-01-16 10:19:30 +08:00
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,
})
}
2026-06-24 16:50:04 +08:00
// Error 错误响应HTTP 状态恒为 200通过 code 区分业务状态
2026-01-16 10:19:30 +08:00
func Error(c *gin.Context, code int, msg string) {
2026-06-24 16:50:04 +08:00
c.JSON(http.StatusOK, Response{
2026-01-16 10:19:30 +08:00
Code: code,
Message: msg,
Result: nil,
})
}
// ServerError 服务器错误 (Code 500)
func ServerError(c *gin.Context, err error) {
2026-06-24 16:50:04 +08:00
c.JSON(http.StatusOK, Response{
2026-01-16 10:19:30 +08:00
Code: 500,
Message: err.Error(),
Result: nil,
})
}