base_controller.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package controllers
  2. import (
  3. "Medical_ERP/common/response"
  4. "encoding/json"
  5. "errors"
  6. "github.com/beego/beego/v2/core/validation"
  7. "github.com/beego/beego/v2/server/web"
  8. "reflect"
  9. "strings"
  10. )
  11. type BaseController struct {
  12. web.Controller
  13. }
  14. func (c *BaseController) OK(data any, msg string) {
  15. c.Data["json"] = response.OK(data, msg)
  16. c.ServeJSON()
  17. return
  18. }
  19. // Error 通常错误数据处理
  20. func (c *BaseController) Error(code int, err error, msg string) {
  21. c.Data["json"] = response.Error(code, err, msg)
  22. c.ServeJSON()
  23. return
  24. }
  25. // PageOK 分页数据处理
  26. func (c *BaseController) PageOK(result interface{}, count int, pageIndex int, pageSize int, msg string) {
  27. c.Data["json"] = response.PageOK(result, count, pageIndex, pageSize, msg)
  28. c.ServeJSON()
  29. return
  30. }
  31. func (c *BaseController) ParseAndValidate(requestBody *[]byte, reqData interface{}) error {
  32. valueType := reflect.ValueOf(reqData).Elem().Type() // 获取结构体类型
  33. newStruct := reflect.New(valueType).Interface() // 创建新的结构体
  34. if err := json.Unmarshal(*requestBody, newStruct); err != nil {
  35. return err
  36. }
  37. v := validation.Validation{}
  38. status, err := v.Valid(newStruct)
  39. if err != nil {
  40. return err
  41. }
  42. if !status {
  43. for _, err := range v.Errors {
  44. // 获取 newStruct 指向的真实结构体的类型
  45. structType := reflect.Indirect(reflect.ValueOf(newStruct)).Type()
  46. field, _ := structType.FieldByName(err.Field)
  47. alias := field.Tag.Get("alias")
  48. message := strings.Replace(err.Message, err.Field, alias, 1)
  49. return errors.New(message)
  50. }
  51. }
  52. reflect.ValueOf(reqData).Elem().Set(reflect.ValueOf(newStruct).Elem())
  53. return nil
  54. }