draft
This commit is contained in:
73
backend/internal/api/handler/response.go
Normal file
73
backend/internal/api/handler/response.go
Normal file
@@ -0,0 +1,73 @@
|
||||
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 ""
|
||||
}
|
||||
Reference in New Issue
Block a user