golang validator で config file なんかをいい感じに扱う
code:go
// 本家 examples より抜粋
type User struct {
FirstName string validate:"required"
LastName string validate:"required"
Age uint8 validate:"gte=0,lte=130"
Email string validate:"required,email"
Gender string validate:"oneof=male female prefer_not_to"
FavouriteColor string validate:"iscolor" // alias for 'hexcolor|rgb|rgba|hsl|hsla'
Addresses []*Address validate:"required,dive,required" // a person can have a home and cottage...
}
これに、json tag や UnmarshalJSON での初期値反映なんかをやれば、yaml や json の config をいい感じに validation しつつ struct に落とし込める
code:go
func (u *User) UnmarshalJSON(b []byte) error {
type innerUser User
inner := &innerUser{
FavouriteColor: "red",
}
if err := json.Unmarshal(b, inner); err != nil {
return err
}
*u = User(*inner)
return nil
}