优化数据验证 #1
23
run.go
23
run.go
@ -23,9 +23,9 @@ import (
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 14:18 2024/4/29
|
||||
func RunForStruct(sourceData any, ruleList []*define.FieldRule) (map[string]any, error) {
|
||||
func RunForStruct(sourceData any, ruleList []*define.FieldRule, receiver any) error {
|
||||
if nil == sourceData {
|
||||
return map[string]any{}, nil
|
||||
return nil
|
||||
}
|
||||
byteData, _ := json.Marshal(sourceData)
|
||||
var (
|
||||
@ -36,12 +36,9 @@ func RunForStruct(sourceData any, ruleList []*define.FieldRule) (map[string]any,
|
||||
d := json.NewDecoder(bytes.NewReader(byteData))
|
||||
d.UseNumber()
|
||||
if err = d.Decode(&sourceMapData); nil != err {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
if err = Run(sourceMapData, ruleList); nil != err {
|
||||
return nil, err
|
||||
}
|
||||
return sourceMapData, nil
|
||||
return Run(sourceMapData, ruleList, receiver)
|
||||
}
|
||||
|
||||
// Run 运行参数验证
|
||||
@ -49,7 +46,7 @@ func RunForStruct(sourceData any, ruleList []*define.FieldRule) (map[string]any,
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 14:13 2024/4/29
|
||||
func Run(sourceData map[string]any, ruleList []*define.FieldRule) error {
|
||||
func Run(sourceData map[string]any, ruleList []*define.FieldRule, receiver any) error {
|
||||
for _, itemRule := range ruleList {
|
||||
itemRule.DefaultValue = nil
|
||||
}
|
||||
@ -57,12 +54,13 @@ func Run(sourceData map[string]any, ruleList []*define.FieldRule) error {
|
||||
if nil != err {
|
||||
return err
|
||||
}
|
||||
sourceData = make(map[string]any)
|
||||
if nil != receiver {
|
||||
d := json.NewDecoder(bytes.NewReader(byteData))
|
||||
d.UseNumber()
|
||||
if err := d.Decode(&sourceData); nil != err {
|
||||
if err := d.Decode(&receiver); nil != err {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -76,6 +74,7 @@ func RunWithResult(sourceData map[string]any, ruleList []*define.FieldRule) ([]b
|
||||
sourceData = make(map[string]any)
|
||||
}
|
||||
byteData, _ := json.Marshal(sourceData)
|
||||
resultByteData, _ := json.Marshal(sourceData)
|
||||
for _, itemRule := range ruleList {
|
||||
if len(itemRule.Path) == 0 {
|
||||
// 未指定验证数据位置
|
||||
@ -89,11 +88,11 @@ func RunWithResult(sourceData map[string]any, ruleList []*define.FieldRule) ([]b
|
||||
} else {
|
||||
if !itemRule.DisableRewrite {
|
||||
// 更新数据
|
||||
byteData, _ = sjson.SetBytes(byteData, itemRule.Path, formatValue)
|
||||
resultByteData, _ = sjson.SetBytes(resultByteData, itemRule.Path, formatValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
return byteData, nil
|
||||
return resultByteData, nil
|
||||
}
|
||||
|
||||
// checkRuleConditionRequiredRule 校验有条件必传
|
||||
|
Loading…
Reference in New Issue
Block a user