12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- 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{}
- Success bool `description:"true 执行成功,false 执行失败"`
- //IsSendEmail bool `json:"-" description:"true 发送邮件,false 不发送邮件"`
- //IsAddLog bool `json:"-" 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
- }
|