|
- // Package validation uses github.com/go-playground/validator/v10 for API request validation.
- package validation
-
- import (
- "fmt"
-
- "github.com/go-playground/validator/v10"
- )
-
- var defaultValidator = validator.New()
-
- // Struct validates s and returns the first validation error as a readable message, or nil.
- func Struct(s interface{}) error {
- err := defaultValidator.Struct(s)
- if err == nil {
- return nil
- }
- if errs, ok := err.(validator.ValidationErrors); ok && len(errs) > 0 {
- fe := errs[0]
- return fmt.Errorf("%s: %s", fe.Field(), fe.Tag())
- }
- return err
- }
-
- // Var validates a single value with the given tag (e.g. "required") and returns an error or nil.
- func Var(field interface{}, tag string) error {
- err := defaultValidator.Var(field, tag)
- if err == nil {
- return nil
- }
- if errs, ok := err.(validator.ValidationErrors); ok && len(errs) > 0 {
- fe := errs[0]
- return fmt.Errorf("%s", fe.Tag())
- }
- return err
- }
|