Files
web_template/internal/handler/response.go
2026-07-10 10:06:30 +00:00

50 lines
1.2 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 handler
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Response 统一响应结构
type Response struct {
Code int `json:"code"` // 0=成功,非0=失败
Message string `json:"message"` // 提示信息
Data interface{} `json:"data"` // 业务数据
}
// Success 成功响应
func Success(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, Response{Code: 0, Message: "success", Data: data})
}
// SuccessMsg 成功响应(仅消息,无数据)
func SuccessMsg(c *gin.Context, msg string) {
c.JSON(http.StatusOK, Response{Code: 0, Message: msg, Data: nil})
}
// Fail 失败响应
func Fail(c *gin.Context, httpCode int, msg string) {
c.JSON(httpCode, Response{Code: 1, Message: msg, Data: nil})
}
// FailBadRequest 400 错误
func FailBadRequest(c *gin.Context, msg string) {
Fail(c, http.StatusBadRequest, msg)
}
// FailUnauthorized 401 未授权
func FailUnauthorized(c *gin.Context, msg string) {
Fail(c, http.StatusUnauthorized, msg)
}
// FailForbidden 403 禁止访问
func FailForbidden(c *gin.Context, msg string) {
Fail(c, http.StatusForbidden, msg)
}
// FailInternal 500 服务器内部错误
func FailInternal(c *gin.Context, msg string) {
Fail(c, http.StatusInternalServerError, msg)
}