package response import ( "electricity_bill_calc/config" "net/http" "github.com/gin-gonic/gin" ) type Result struct { Ctx *gin.Context } type BaseResponse struct { Code int `json:"code"` Message string `json:"message"` } type PagedResponse struct { Page int `json:"current"` Size int `json:"pageSize"` Total int64 `json:"total"` } func NewResult(ctx *gin.Context) *Result { return &Result{Ctx: ctx} } // 操作出错(未成功)响应 func (r *Result) Error(code int, msg string) { res := BaseResponse{} res.Code = code res.Message = msg r.Ctx.JSON(http.StatusInternalServerError, res) } // 简易操作成功信息 func (r *Result) Success(msg string) { res := BaseResponse{} res.Code = http.StatusOK res.Message = msg r.Ctx.JSON(http.StatusOK, res) } // 数据成功创建 func (r *Result) Created(msg string) { res := BaseResponse{} res.Code = http.StatusCreated res.Message = msg r.Ctx.JSON(http.StatusCreated, res) } // 数据成功更新 func (r *Result) Updated(msg string) { res := BaseResponse{} res.Code = http.StatusAccepted res.Message = msg r.Ctx.JSON(http.StatusAccepted, res) } // 数据已成功删除 func (r *Result) Deleted(msg string) { res := BaseResponse{} res.Code = http.StatusNoContent res.Message = msg r.Ctx.JSON(http.StatusNoContent, res) } // 指定操作未被接受 func (r *Result) NotAccept(msg string) { res := BaseResponse{} res.Code = http.StatusNotAcceptable res.Message = msg r.Ctx.JSON(http.StatusNotAcceptable, res) } // 数据未找到 func (r *Result) NotFound(msg string) { res := BaseResponse{} res.Code = http.StatusNotFound res.Message = msg r.Ctx.JSON(http.StatusNotFound, res) } // 快速自由JSON格式响应 // ! 注意,给定的map中,同名的键会被覆盖。 func (r *Result) Json(status, code int, msg string, payloads ...map[string]interface{}) { var finalPayload = make(map[string]interface{}, 0) finalPayload["code"] = code finalPayload["message"] = &msg for _, m := range payloads { for k, v := range m { finalPayload[k] = v } } r.Ctx.JSON(status, finalPayload) } func NewPagedResponse(page int, total int64) *PagedResponse { return &PagedResponse{page, config.ServiceSettings.ItemsPageSize, total} } func (r PagedResponse) ToMap() map[string]interface{} { return gin.H{ "current": r.Page, "pageSize": r.Size, "total": r.Total, } }