core/infra/response.go

37 lines
615 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 {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data"`
}
func (reply *Reply) Success(ctx *gin.Context, data any) {
reply.Code = 200
2025-02-11 14:22:14 +08:00
reply.Data = data
2025-02-07 20:33:27 +08:00
if data == nil {
reply.Data = ""
}
ctx.JSON(200, reply)
}
func (reply *Reply) Error(ctx *gin.Context, err error) {
reply.Code = 500
// Status code defaults to 500
e, ok := status.FromError(err)
if ok {
reply.Code = int(e.Code())
}
reply.Msg = e.Message()
// Send error
ctx.JSON(200, reply)
}