github.com/SupenBysz/gf-admin-community@v0.7.4/utility/sys_rules/custom-rules.go (about) 1 package sys_rules 2 3 import ( 4 "context" 5 "fmt" 6 "github.com/SupenBysz/gf-admin-community/sys_model" 7 "github.com/gogf/gf/v2/container/gmap" 8 "github.com/gogf/gf/v2/frame/g" 9 "github.com/gogf/gf/v2/net/ghttp" 10 "github.com/gogf/gf/v2/os/gstructs" 11 "github.com/gogf/gf/v2/text/gstr" 12 "github.com/gogf/gf/v2/util/gvalid" 13 "reflect" 14 ) 15 16 func RequiredLicense() { 17 gvalid.RegisterRule("required-license", func(ctx context.Context, in gvalid.RuleFuncInput) error { 18 license := ghttp.RequestFromCtx(ctx).Get("license") 19 if license == nil { 20 return nil 21 } 22 23 licenseFields, _ := gstructs.Fields(gstructs.FieldsInput{ 24 Pointer: &sys_model.PersonLicense{}, 25 RecursiveOption: 0, 26 }) 27 28 rulesMap := gmap.StrStrMap{} 29 30 for _, field := range licenseFields { 31 tag := field.Tag("v") 32 33 tag = gstr.Replace(tag, "-license", "") 34 35 if tag == "" || gstr.HasPrefix(tag, "#") { 36 continue 37 } 38 39 rulesMap.Set(field.TagJsonName(), tag) 40 41 data := gmap.NewStrAnyMapFrom(license.MapStrAny()) 42 43 tmpArr := gstr.Split(tag, "#") 44 45 value := data.GetVar(field.TagJsonName()).Val() 46 47 vObj := g.Validator() 48 49 if value == nil && field.Field.Type == reflect.TypeOf("") { 50 value = "" 51 } 52 53 vObj = vObj.Data(value).Rules(tmpArr[0]) 54 55 if len(tmpArr) == 2 { 56 vObj = vObj.Messages(tmpArr[1]) 57 } 58 59 if err := vObj.Run(context.Background()); err != nil { 60 fmt.Println("check value err:", err) 61 return err 62 } 63 } 64 65 return nil 66 }) 67 }