Overview
model — defaults & validation for Go structs
model
is a tiny helper that binds a Model to your struct. It can:
- Set defaults from struct tags like
default:"…"
anddefaultElem:"…"
. - Validate fields using named rules from
validate:"…"
andvalidateElem:"…"
. - Accumulate all issues into a single ValidationError (no fail-fast).
- Recurse through nested structs, pointers, slices/arrays, and map values.
It’s designed to be small, explicit, and type-safe (uses generics). You register rules (via NewRule
) and model
handles traversal, dispatch, and error reporting. Built‑in rules are always available implicitly (you don’t have to register them unless you want to override their behavior).
- Repository: github.com/ygrebnov/model
- API Docs: pkg.go.dev/github.com/ygrebnov/model
Quick start
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/ygrebnov/model"
)
type User struct {
Name string `default:"Anonymous" validate:"nonempty"`
Age int `default:"18" validate:"positive,nonzero"`
Timeout time.Duration `default:"1s"`
}
func main() {
u := User{}
m, err := model.New(&u,
model.WithDefaults[User](),
model.WithValidation[User](context.Background()),
)
if err != nil {
var ve *model.ValidationError
if errors.As(err, &ve) {
b, _ := json.MarshalIndent(ve, "", " ")
fmt.Println(string(b))
} else {
fmt.Println("error:", err)
}
return
}
_ = m
fmt.Printf("User after defaults: %+v\n", u)
}
See Installation and Examples for more.