I'm trying to learn golang custom validation but running into a lot of trouble. Here's the code for what I've been attempting:
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)
}
You can see the validation logic that I'm attempting in the code comments...If the DropShip
field is true, then I need to submit the Country
and Age
to another API to see if this team member is eligible.
The problem is that I'm struggling with the reflect
library to access the Country
and Age
fields in the TeamMember
struct. The fmt.Println(c.(TeamMember))
line crashes my program.
Can someone give me an example of how to access the other TeamMember fields? Or is my approach to validation in violation of the idiomatic way of validating in golang?
Aucun commentaire:
Enregistrer un commentaire