我正在try 学习Golang定制验证,但遇到了很多麻烦.以下是我一直在try 的代码:
package main
import (
"reflect"
"github.com/go-playground/validator/v10"
"fmt"
)
type TeamMember struct {
Country string
Age int
DropShip bool `validate:"is_eligible"`
}
func CustomValidation(fl validator.FieldLevel) bool {
/*
if(DropShip == true) {
httpresponse = curl https://3rd-party-api.com/?country=<Country>&age=<Age>
return httpresponse.code == 200
}
return false
*/
b := fl.Parent()
fmt.Println(reflect.TypeOf(b))
fmt.Println(reflect.ValueOf(b))
c := reflect.ValueOf(b).Interface()
fmt.Println(c.(TeamMember))
fmt.Println("============")
return true
}
func main() {
var validate *validator.Validate
validate = validator.New(validator.WithRequiredStructEnabled())
_ = validate.RegisterValidation("is_eligible", CustomValidation)
teammember := TeamMember{"Canada", 34, true}
validate.Struct(teammember)
}
您可以在代码注释中看到我正在try 的验证逻辑……如果DropShip
字段为真,那么我需要将Country
和Age
提交给另一个API,以查看该团队成员是否符合条件.
问题是,我很难使用reflect
库来访问TeamMember
struct 中的Country
和Age
字段.fmt.Println(c.(TeamMember))
行使我的程序崩溃.
有人能给我一个如何访问其他团队成员字段的例子吗?或者,我的验证方法违反了golang 语中惯用的验证方式?