Skip to main content

Examples

Minimal example

package main

import (
"context"
"encoding/json"
"errors"
"fmt"
"time"

"github.com/ygrebnov/model"
)

type Cfg struct {
Name string `default:"svc" validate:"nonempty"`
Wait time.Duration `default:"500ms"`
}

func main() {
cfg := Cfg{}
m, err := model.New(&cfg,
model.WithDefaults[Cfg](),
model.WithValidation[Cfg](context.Background()), // built-ins supply nonempty automatically
)
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("OK: %+v\n", cfg)
}

Running the examples

The examples live directly in the package as Example* functions and are executed by go test.

# run unit tests and example functions
go test ./...

# run only examples
go test -run Example ./...

Browse examples: