core/infra/response.go

44 lines
930 B
Go
Raw Normal View History

2025-02-07 20:33:27 +08:00
package infra
import (
"github.com/gin-gonic/gin"
"google.golang.org/grpc/status"
)
2025-02-11 11:06:35 +08:00
var Response Reply
2025-02-07 20:33:27 +08:00
type Reply struct {
2025-04-18 19:11:50 +08:00
Code int32 `json:"code"`
Message string `json:"message"`
Result any `json:"result"`
2025-02-07 20:33:27 +08:00
}
// Success writes a normalized success payload with code=0.
2025-02-07 20:33:27 +08:00
func (reply *Reply) Success(ctx *gin.Context, data any) {
2025-04-18 19:11:50 +08:00
reply.Code = 0
reply.Result = data
reply.Message = ""
2025-02-07 20:33:27 +08:00
if data == nil {
2025-04-18 19:11:50 +08:00
reply.Result = ""
2025-02-07 20:33:27 +08:00
}
ctx.JSON(200, reply)
}
// Error converts an error (including gRPC status) to a normalized payload.
// Error converts an error (including gRPC status) to a normalized payload.
2025-02-07 20:33:27 +08:00
func (reply *Reply) Error(ctx *gin.Context, err error) {
reply.Code = 500
2025-04-18 19:11:50 +08:00
reply.Result = ""
2025-02-07 20:33:27 +08:00
// Status code defaults to 500
e, ok := status.FromError(err)
if ok {
2025-04-18 19:11:50 +08:00
reply.Code = int32(e.Code())
reply.Message = e.Message()
} else {
reply.Message = err.Error()
2025-02-07 20:33:27 +08:00
}
// Send error
ctx.JSON(200, reply)
}