forked from free-lancers/electricity_bill_calc_service
115 lines
2.7 KiB
Go
115 lines
2.7 KiB
Go
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) response(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 (r *Result) Failure(code int, msg string) {
|
|
r.response(http.StatusInternalServerError, code, msg)
|
|
}
|
|
|
|
// 操作出错(未成功)响应
|
|
func (r *Result) Error(code int, msg string) {
|
|
r.response(http.StatusOK, code, msg)
|
|
}
|
|
|
|
// 用户未获得授权)响应
|
|
func (r *Result) Unauthorized(msg string) {
|
|
r.response(http.StatusOK, http.StatusUnauthorized, msg)
|
|
}
|
|
|
|
// 简易操作成功信息
|
|
func (r *Result) Success(msg string, payloads ...map[string]interface{}) {
|
|
r.response(http.StatusOK, http.StatusOK, msg, payloads...)
|
|
}
|
|
|
|
// 数据成功创建
|
|
func (r *Result) Created(msg string, payloads ...map[string]interface{}) {
|
|
r.response(http.StatusOK, http.StatusCreated, msg, payloads...)
|
|
}
|
|
|
|
// 数据成功更新
|
|
func (r *Result) Updated(msg string) {
|
|
r.response(http.StatusOK, http.StatusAccepted, msg)
|
|
}
|
|
|
|
// 数据已成功删除
|
|
func (r *Result) Deleted(msg string) {
|
|
r.response(http.StatusOK, http.StatusNoContent, msg)
|
|
}
|
|
|
|
// 指定操作未被接受
|
|
func (r *Result) BadRequest(msg string) {
|
|
r.response(http.StatusOK, http.StatusBadRequest, msg)
|
|
}
|
|
|
|
// 指定操作未被接受
|
|
func (r *Result) NotAccept(msg string) {
|
|
r.response(http.StatusOK, http.StatusNotAcceptable, msg)
|
|
}
|
|
|
|
// 数据未找到
|
|
func (r *Result) NotFound(msg string) {
|
|
r.response(http.StatusOK, http.StatusNotFound, msg)
|
|
}
|
|
|
|
// 数据存在冲突
|
|
func (r *Result) Conflict(msg string) {
|
|
r.response(http.StatusOK, http.StatusConflict, msg)
|
|
}
|
|
|
|
// 快速自由JSON格式响应
|
|
// ! 注意,给定的map中,同名的键会被覆盖。
|
|
func (r *Result) Json(code int, msg string, payloads ...map[string]interface{}) {
|
|
r.response(http.StatusOK, code, msg, payloads...)
|
|
}
|
|
|
|
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,
|
|
}
|
|
}
|