1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- package controllers
- import (
- "encoding/json"
- "errors"
- logger "eta_mini_ht_api/common/component/log"
- "eta_mini_ht_api/common/exception"
- "eta_mini_ht_api/common/http"
- "github.com/beego/beego/v2/server/web"
- )
- type WrapData struct {
- Msg string
- Data interface{}
- }
- type BaseResponse struct {
- Ret int `description:"返回状态码"`
- Msg string
- ErrMsg string
- ErrCode int
- Data interface{} `json:"data,omitempty"`
- Success bool `description:"true 执行成功,false 执行失败"`
- }
- type BaseController struct {
- web.Controller
- }
- func (b *BaseController) FailResponse(errInfo error, msg string) {
- var retData BaseResponse
- var etaError *exception.EtaError
- if !errors.As(errInfo, &etaError) {
- etaError = exception.New(exception.UnknownError)
- }
- retData = BaseResponse{
- Ret: 200,
- Msg: msg,
- ErrMsg: etaError.ErrorMsg,
- ErrCode: etaError.ErrorCode,
- Data: nil}
- b.Data["json"] = retData
- b.ServeJSON()
- }
- // JsonResult /*
- func (b *BaseController) JsonResult(status int, errCode int, errMsg string, msg string, success bool, data interface{}) {
- retData := BaseResponse{
- Ret: status,
- Msg: msg,
- ErrMsg: errMsg,
- ErrCode: errCode,
- Data: data,
- Success: success}
- b.Ctx.Output.SetStatus(status)
- b.Data["json"] = retData
- b.ServeJSON()
- }
- func (b *BaseController) GetPostParams(data interface{}) {
- err := json.Unmarshal(b.Ctx.Input.RequestBody, data)
- if err != nil {
- logger.Error("解析请求参数失败:%v", err)
- data = nil
- }
- }
- // Wrap ControllerWrap 是一个用于封装控制器方法的函数
- func Wrap(a *BaseController, fn func() (*WrapData, error)) {
- result, err := fn()
- if err != nil {
- logger.Error("%v", err)
- a.FailResponse(err, result.Msg)
- return
- }
- a.JsonResult(http.GetHttpStatusByAlias("ok"), http.ErrOK, "", result.Msg, http.Success, result.Data)
- }
- func (b *BaseController) InitWrapData(msg string) *WrapData {
- return &WrapData{Msg: msg}
- }
- func (b *BaseController) SuccessResult(msg string, data interface{}, wrapData *WrapData) {
- wrapData.Msg = msg
- wrapData.Data = data
- }
- func (b *BaseController) FailedResult(msg string, wrapData *WrapData) {
- wrapData.Msg = msg
- }
|