You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
paopao-ce/pkg/app/app.go

64 lines
1.1 KiB

2 years ago
package app
import (
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/pkg/errcode"
2 years ago
)
type Response struct {
Ctx *gin.Context
}
type Pager struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalRows int64 `json:"total_rows"`
}
func NewResponse(ctx *gin.Context) *Response {
return &Response{Ctx: ctx}
}
func (r *Response) ToResponse(data any) {
2 years ago
hostname, _ := os.Hostname()
if data == nil {
data = gin.H{
"code": 0,
"msg": "success",
"tracehost": hostname,
}
} else {
data = gin.H{
"code": 0,
"msg": "success",
"data": data,
"tracehost": hostname,
}
}
r.Ctx.JSON(http.StatusOK, data)
}
func (r *Response) ToResponseList(list any, totalRows int64) {
2 years ago
r.ToResponse(gin.H{
"list": list,
"pager": Pager{
Page: GetPage(r.Ctx),
PageSize: GetPageSize(r.Ctx),
TotalRows: totalRows,
},
})
}
func (r *Response) ToErrorResponse(err *errcode.Error) {
response := gin.H{"code": err.Code(), "msg": err.Msg()}
details := err.Details()
if len(details) > 0 {
response["details"] = details
}
r.Ctx.JSON(err.StatusCode(), response)
}