Context:
Using a custom Binder and Validator in Echo Framework. The binder use a signature of (interface{}, echo.Context), but a pointer is always passed and checked by echo.DefaultBinder.
I'm having trouble validating an array of struct for some reason, when an array is passed for some unknown reason. Therefore, I'm trying to validate each elements in the interface, if this interface is an Array or a Slice.
Problem:
I cannot find a way to both cast the interface to a value instead of a pointer and iterate trough the values of this array to validate each of them.
My Code so far:
func (cb *CustomBinder) Bind(i interface{}, c echo.Context) error {
db := new(echo.DefaultBinder)
validate := validator.New()
if err := db.Bind(i, c); err != nil {
return err
}
kind := reflect.ValueOf(i).Elem().Kind()
if kind == reflect.Array || kind == reflect.Slice {
// ... Iteration and Validation
} else {
if err := validate.Struct(i); err != nil {
return err
}
}
return nil
}
I would rather use type assertions than reflection because reflection is slow in terms of performance and not friendly to use.
To illustrate what I mean, check this example code where I have a function that accepts an argument of type
interface{}and prints the values according to the data type,Output:
Index: 0 Value: value1
Index: 1 Value: value2
Key: key1 Value: value1
value1
Playground: https://play.golang.org/p/TMfojVdoi5b
You can use this logic of type assertion in your code to check if the
interfaceis a slice and iterate over it for validation.Something like this,