base_controller.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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{} `json:"data,omitempty"`
  20. Success bool `description:"true 执行成功,false 执行失败"`
  21. }
  22. type BaseController struct {
  23. web.Controller
  24. }
  25. func (b *BaseController) FailResponse(errInfo error, msg string) {
  26. var retData BaseResponse
  27. var etaError *exception.EtaError
  28. if !errors.As(errInfo, &etaError) {
  29. etaError = exception.New(exception.UnknownError)
  30. }
  31. retData = BaseResponse{
  32. Ret: 200,
  33. Msg: msg,
  34. ErrMsg: etaError.ErrorMsg,
  35. ErrCode: etaError.ErrorCode,
  36. Data: nil}
  37. b.Data["json"] = retData
  38. b.ServeJSON()
  39. }
  40. // JsonResult /*
  41. func (b *BaseController) JsonResult(status int, errCode int, errMsg string, msg string, success bool, data interface{}) {
  42. retData := BaseResponse{
  43. Ret: status,
  44. Msg: msg,
  45. ErrMsg: errMsg,
  46. ErrCode: errCode,
  47. Data: data,
  48. Success: success}
  49. b.Ctx.Output.SetStatus(status)
  50. b.Data["json"] = retData
  51. b.ServeJSON()
  52. }
  53. func (b *BaseController) GetPostParams(data interface{}) {
  54. err := json.Unmarshal(b.Ctx.Input.RequestBody, data)
  55. if err != nil {
  56. logger.Error("解析请求参数失败:%v", err)
  57. data = nil
  58. }
  59. }
  60. // Wrap ControllerWrap 是一个用于封装控制器方法的函数
  61. func Wrap(a *BaseController, fn func() (*WrapData, error)) {
  62. result, err := fn()
  63. if err != nil {
  64. logger.Error("%v", err)
  65. a.FailResponse(err, result.Msg)
  66. return
  67. }
  68. a.JsonResult(http.GetHttpStatusByAlias("ok"), http.ErrOK, "", result.Msg, http.Success, result.Data)
  69. }
  70. func (b *BaseController) InitWrapData(msg string) *WrapData {
  71. return &WrapData{Msg: msg}
  72. }
  73. func (b *BaseController) SuccessResult(msg string, data interface{}, wrapData *WrapData) {
  74. wrapData.Msg = msg
  75. wrapData.Data = data
  76. }
  77. func (b *BaseController) FailedResult(msg string, wrapData *WrapData) {
  78. wrapData.Msg = msg
  79. }