您可能想要使用反射来遍历该结构的字段,获取
validate每个字段的标签,然后检查该字段。这意味着您必须在结构级别上进行验证。否则,如果将类似的东西传递
myInstance.OwnerID给函数,则会丢失与之关联的标签。
这段代码循环遍历一个结构的字段,并
validate为每个字段获取标签:
func checkStruct(v interface{}) error { val := reflect.ValueOf(v) // Iterate through fields for i := 0; i < val.NumField(); i++ { // Lookup the validate tag field := val.Type().Field(i) tags := field.Tag validate, ok := tags.Lookup("validate") if !ok { // No validate tag. continue } // Get the value of the field. fieldValue := val.Field(i) // Validation logic here. fmt.Println("field", field.Name, "has validate tag", validate, "and value", fieldValue.Interface()) } return nil}例如,我们可以将以下内容传递给它
CarModel:
checkStruct(CarModel{ OwnerID: 2, Type: "B", A: "http://google.com", B: "192.168.1.1",})它会打印出以下内容:
field OwnerID has validate tag nonzero and value 2field Type has validate tag regexp=(?)(A|B) and value Bfield A has validate tag isurl and value http://google.comfield B has validate tag isip and value 192.168.1.1



