Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tagged defaults #45

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

tagged defaults #45

wants to merge 1 commit into from

Conversation

willbtlr
Copy link

@willbtlr willbtlr commented May 1, 2023

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!

@willbtlr
Copy link
Author

willbtlr commented May 1, 2023

Ah it looks like IsExported() needs go >= 1.17. I could just check the case of the first char of the field?

@servusdei2018
Copy link

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.

@@ -34,6 +34,16 @@ func Set(ptr interface{}) error {

for i := 0; i < t.NumField(); i++ {
if defaultVal := t.Field(i).Tag.Get(fieldName); defaultVal != "-" {
if t.Field(i).IsExported() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if t.Field(i).IsExported() {

// Check whether the field is exported
if t.Field(i).PkgPath != "" {

@creasty
Copy link
Owner

creasty commented Aug 14, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants