Using oneof with Default Values in go-playground/validator
The go-playground/validator package doesn't natively support default values for oneof validations, but you can implement this behavior in a few ways:
Option 1: Custom Validation Function
package main
import (
"github.com/go-playground/validator/v10"
"reflect"
)
func main() {
validate := validator.New()
// Register custom validation function
validate.RegisterValidation("oneof_with_default", func(fl validator.FieldLevel) bool {
// Get the struct field value
value := fl.Field().Interface()
// Get the struct field tag
tag := fl.Field().StructField().Tag.Get("oneof_with_default")
// Split the tag into options and default value
parts := strings.Split(tag, "|")
if len(parts) < 2 {
return false
}
options := parts[0]
defaultValue := parts[1]
// Check if value is in options or matches default
for _, opt := range strings.Split(options, ",") {
if reflect.DeepEqual(value, opt) {
return true
}
}
// If not in options, check if it matches default
return reflect.DeepEqual(value, defaultValue)
})
// Example struct
type Example struct {
Field string `validate:"oneof_with_default=opt1,opt2,opt3|default_value"`
}
}
Option 2: Pre-processing Before Validation
func setDefaults(obj interface{}) {
val := reflect.ValueOf(obj).Elem()
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
tag := field.Tag.Get("oneof_with_default")
if tag != "" {
parts := strings.Split(tag, "|")
if len(parts) == 2 {
options := parts[0]
defaultValue := parts[1]
// If field is empty, set default
if reflect.DeepEqual(val.Field(i).Interface(), reflect.Zero(val.Field(i).Type()).Interface()) {
val.Field(i).Set(reflect.ValueOf(defaultValue))
}
}
}
}
}
// Usage:
setDefaults(yourStruct)
validate.Struct(yourStruct)
Option 3: Using Custom Struct Tag
type Example struct {
Field string `validate:"oneof=opt1,opt2,opt3" default:"default_value"`
}
// Then implement a custom validator that checks both
Example with Full Implementation
Here's a more complete example:
package main
import (
"fmt"
"reflect"
"strings"
"github.com/go-playground/validator/v10"
)
type Config struct {
Environment string `validate:"oneof_with_default=dev,staging,prod|dev"`
Debug bool `validate:"oneof_with_default=true,false|false"`
}
func main() {
validate := validator.New()
// Register custom validation
validate.RegisterValidation("oneof_with_default", func(fl validator.FieldLevel) bool {
value := fl.Field().Interface()
tag := fl.Field().StructField().Tag.Get("oneof_with_default")
parts := strings.Split(tag, "|")
if len(parts) != 2 {
return false
}
options := strings.Split(parts[0], ",")
defaultValue := parts[1]
// Check if value is in options
for _, opt := range options {
if reflect.DeepEqual(value, opt) {
return true
}
}
// If not in options, check if it matches default
return reflect.DeepEqual(value, defaultValue)
})
// Test cases
tests := []struct {
config Config
valid bool
}{
{Config{Environment: "dev"}, true},
{Config{Environment: "staging"}, true},
{Config{Environment: "prod"}, true},
{Config{Environment: ""}, true}, // should use default "dev"
{Config{Environment: "invalid"}, false},
{Config{Debug: true}, true},
{Config{Debug: false}, true},
{Config{Debug: true}, true},
}
for _, test := range tests {
err := validate.Struct(test.config)
if (err == nil) != test.valid {
fmt.Printf("Test failed: %+v\n", test.config)
} else {
fmt.Printf("Test passed: %+v\n", test.config)
}
}
}
This approach gives you the flexibility to specify both the allowed values and a default value in your struct tags.