Give your struct tags a job.
structwalker
> walk any struct, act on its tags
Every Go project rewrites the same reflection loop for defaults, validation and redaction. This is that loop, written once. You say what a tag means and it does the walking.
// add it to your module
$ go get github.com/rjp2525/structwalker
// standard library only
const dependencies = 0
type Config struct {
Port int `default:"8080"`
Timeout time.Duration `default:"30s"`
DB struct {
Host string `default:"localhost"`
}
}
w := structwalker.New()
w.Handle("default", func(ctx structwalker.FieldContext) error {
if ctx.IsZero() {
return ctx.SetValue(ctx.Tag.Raw)
}
return nil
})
var cfg Config
err := w.Walk(&cfg)
// cfg.Port == 8080
// cfg.Timeout == 30 * time.Second
// cfg.DB.Host == "localhost"
One handler per tag
Register what validate, default or mask means. One walk runs them all, in the order you choose.
Or just a for loop
for f := range structwalker.Fields(&cfg) visits every field. Nothing to register and break works.
A setter that converts
SetValue("30s") fills a time.Duration. Numbers, bools, pointers and text unmarshalers work too. It never stores a value that didn't fit.
The whole struct
Nested structs and pointers by default. Slices, maps and interfaces when you ask. Cycles are detected and every field knows its path.
errorsErrors that say where
Stop at the first error or collect them all. Each one carries the field's path, which is most of a validation message.
speedFast enough to forget about
Reflection work is cached per type. A flat struct walks in about 200ns with zero allocations and a walker is safe to share.
// requirements
go 1.26+ · dependencies none · license MIT