tagged defaults
Hey there! I'd love to be able to set a custom default for a type based on the tag like so:
type Duration struct {
time.Duration
}
func (d *Duration) SetTaggedDefaults(tag string) (err error) {
d.Duration, err = time.ParseDuration(tag)
return
}
type TaggedDefaults struct {
Duration Duration `default:"1s"`
}
sample := &TaggedDefaults{}
err := Set(sample)
if err != nil { t.Errorf("unexpected error: %s", err) }
if sample.Duration.Duration != time.Second { t.Errorf("expected 1s for Duration, got %s", sample.Duration.Duration) }
This PR adds the interface and modifies the Set() logic to use it. Added tests to account for success and failure. All tests passing. Thanks!
Ah it looks like IsExported() needs go >= 1.17. I could just check the case of the first char of the field?
See golang/go#41563, basically you'll want to check if t.Field(i).PkgPath != "" (exported). StructField.PkgPath is populated if and only if the field is unexported.
func (d *Duration) SetTaggedDefaults(tag string) (err error) {
I would utilize https://pkg.go.dev/encoding/json#Unmarshaler or https://pkg.go.dev/encoding#TextUnmarshaler interfaces instead.