package controllers import ( "Medical_ERP/common/response" "encoding/json" "errors" "github.com/beego/beego/v2/core/validation" "github.com/beego/beego/v2/server/web" "reflect" "strings" ) type BaseController struct { web.Controller } func (c *BaseController) OK(data any, msg string) { c.Data["json"] = response.OK(data, msg) c.ServeJSON() return } // Error 通常错误数据处理 func (c *BaseController) Error(code int, err error, msg string) { c.Data["json"] = response.Error(code, err, msg) c.ServeJSON() return } // PageOK 分页数据处理 func (c *BaseController) PageOK(result interface{}, count int, pageIndex int, pageSize int, msg string) { c.Data["json"] = response.PageOK(result, count, pageIndex, pageSize, msg) c.ServeJSON() return } func (c *BaseController) ParseAndValidate(requestBody *[]byte, reqData interface{}) error { valueType := reflect.ValueOf(reqData).Elem().Type() // 获取结构体类型 newStruct := reflect.New(valueType).Interface() // 创建新的结构体 if err := json.Unmarshal(*requestBody, newStruct); err != nil { return err } v := validation.Validation{} status, err := v.Valid(newStruct) if err != nil { return err } if !status { for _, err := range v.Errors { // 获取 newStruct 指向的真实结构体的类型 structType := reflect.Indirect(reflect.ValueOf(newStruct)).Type() field, _ := structType.FieldByName(err.Field) alias := field.Tag.Get("alias") message := strings.Replace(err.Message, err.Field, alias, 1) return errors.New(message) } } reflect.ValueOf(reqData).Elem().Set(reflect.ValueOf(newStruct).Elem()) return nil }