base_controller.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. logger "eta_mini_ht_api/common/component/log"
  6. "eta_mini_ht_api/common/exception"
  7. "eta_mini_ht_api/common/http"
  8. "github.com/beego/beego/v2/server/web"
  9. )
  10. type WrapData struct {
  11. Msg string
  12. Data interface{}
  13. }
  14. type BaseResponse struct {
  15. Ret int `description:"返回状态码"`
  16. Msg string
  17. ErrMsg string
  18. ErrCode int
  19. Data interface{}
  20. Success bool `description:"true 执行成功,false 执行失败"`
  21. //IsSendEmail bool `json:"-" description:"true 发送邮件,false 不发送邮件"`
  22. //IsAddLog bool `json:"-" description:"true 新增操作日志,false 不新增操作日志" `
  23. }
  24. type BaseController struct {
  25. web.Controller
  26. }
  27. func (b *BaseController) FailResponse(errInfo error, msg string) {
  28. var retData BaseResponse
  29. var etaError *exception.EtaError
  30. if !errors.As(errInfo, &etaError) {
  31. etaError = exception.New(exception.UnknownError)
  32. }
  33. retData = BaseResponse{
  34. Ret: 200,
  35. Msg: msg,
  36. ErrMsg: etaError.ErrorMsg,
  37. ErrCode: etaError.ErrorCode,
  38. Data: nil}
  39. b.Data["json"] = retData
  40. b.ServeJSON()
  41. }
  42. // JsonResult /*
  43. func (b *BaseController) JsonResult(status int, errCode int, errMsg string, msg string, success bool, data interface{}) {
  44. retData := BaseResponse{
  45. Ret: status,
  46. Msg: msg,
  47. ErrMsg: errMsg,
  48. ErrCode: errCode,
  49. Data: data,
  50. Success: success}
  51. b.Ctx.Output.SetStatus(status)
  52. b.Data["json"] = retData
  53. b.ServeJSON()
  54. }
  55. func (b *BaseController) GetPostParams(data interface{}) {
  56. err := json.Unmarshal(b.Ctx.Input.RequestBody, data)
  57. if err != nil {
  58. logger.Error("解析请求参数失败:%v", err)
  59. data = nil
  60. }
  61. }
  62. // Wrap ControllerWrap 是一个用于封装控制器方法的函数
  63. func Wrap(a *BaseController, fn func() (*WrapData, error)) {
  64. result, err := fn()
  65. if err != nil {
  66. logger.Error("%v", err)
  67. a.FailResponse(err, result.Msg)
  68. return
  69. }
  70. a.JsonResult(http.GetHttpStatusByAlias("ok"), http.ErrOK, "", result.Msg, http.Success, result.Data)
  71. }
  72. func (b *BaseController) InitWrapData(msg string) *WrapData {
  73. return &WrapData{Msg: msg}
  74. }
  75. func (b *BaseController) SuccessResult(msg string, data interface{}, wrapData *WrapData) {
  76. wrapData.Msg = msg
  77. wrapData.Data = data
  78. }
  79. func (b *BaseController) FailedResult(msg string, wrapData *WrapData) {
  80. wrapData.Msg = msg
  81. }