electricity_bill_calc_service/response/base_response.go

99 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package response
import (
"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:"page"`
Size int `json:"pageSize"`
Total int `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)
}