Files
pay-bridge/backend/internal/api/handler/response.go
2026-03-13 15:51:59 +08:00

74 lines
1.6 KiB
Go
Raw 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 string `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
TraceID string `json:"trace_id,omitempty"`
}
// OK 成功响应
func OK(c *gin.Context, data any) {
c.JSON(http.StatusOK, Response{
Code: "0",
Message: "success",
Data: data,
TraceID: traceID(c),
})
}
// Fail 失败响应
func Fail(c *gin.Context, httpStatus int, code, message string) {
c.JSON(httpStatus, Response{
Code: code,
Message: message,
TraceID: traceID(c),
})
}
// BadRequest 400
func BadRequest(c *gin.Context, code, message string) {
Fail(c, http.StatusBadRequest, code, message)
}
// Unauthorized 401
func Unauthorized(c *gin.Context, code, message string) {
Fail(c, http.StatusUnauthorized, code, message)
}
// Forbidden 403
func Forbidden(c *gin.Context, code, message string) {
Fail(c, http.StatusForbidden, code, message)
}
// UnprocessableEntity 422业务规则错误
func UnprocessableEntity(c *gin.Context, code, message string) {
Fail(c, http.StatusUnprocessableEntity, code, message)
}
// InternalError 500
func InternalError(c *gin.Context, code, message string) {
Fail(c, http.StatusInternalServerError, code, message)
}
// BadGateway 502渠道错误
func BadGateway(c *gin.Context, code, message string) {
Fail(c, http.StatusBadGateway, code, message)
}
func traceID(c *gin.Context) string {
if id, exists := c.Get("trace_id"); exists {
if s, ok := id.(string); ok {
return s
}
}
return ""
}