Skip to main content

model

model builds a reusable Binding[T] for a Go struct. A binding compiles the struct schema and validation rules once, then applies defaults, typed values, a snapshot of the process environment, or validation to many values of that type. It can also export field values to a sink.

Use it when configuration or request structs need the same rules at several levels. Tags express local rules; application code controls the order of operations and cross-field conditions.

type Database struct {
Driver string `default:"sqlite" validate:"oneof(sqlite,postgres)"`
MaxOpenConns int `default:"1" validate:"min(1)"`
}

type CLIConfig struct {
Database *Database `default:"dive"`
}

binding, err := model.NewBinding[CLIConfig]()
if err != nil {
return err
}
cfg := CLIConfig{}
if err := binding.ValidateWithDefaults(ctx, &cfg); err != nil {
return err
}

ValidateWithDefaults applies literal defaults, applies environment values captured when the binding was created, and validates. Call the individual methods when you need a different order. These operations can change the object before a later step fails.

Install with go get github.com/ygrebnov/model (Go 1.22 or later). For one-off work, use model.SetDefaults, model.Validate, or model.ValidateWithDefaults.

Start with Validate, the built-in rules, Apply defaults, or the use cases. The API reference covers every exported symbol; the repository contains executable examples.