Files
nl-blogs/server/utils/response.go
2026-06-24 16:50:04 +08:00

51 lines
1.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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,
})
}