ParseWithOptions: add the ability to override defaultTypeParsers#272
Conversation
Codecov ReportPatch coverage:
Additional details and impacted files@@ Coverage Diff @@
## main #272 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 3 3
Lines 430 431 +1
=========================================
+ Hits 430 431 +1
☔ View full report in Codecov by Sentry. |
|
fwiw you can already do this by creating a type wrapping the intended type, and implementing a custom wrapper for it, e.g.: type MyDuration time.Duration
func (t *MyDuration) UnmarshalText(text []byte) error {
sec, err := strconv.ParseInt(string(text), 10, 64)
if err == nil {
*t = MyDuration(time.Duration(sec) * time.Second)
return nil
}
tt, err := time.ParseDuration(string(text))
*t = MyDuration(tt)
return err
}
func TestCustomDurationParser(t *testing.T) {
type config struct {
Dur1 MyDuration `env:"DUR_1"`
Dur2 MyDuration `env:"DUR_2"`
}
t.Setenv("DUR_1", "20m")
t.Setenv("DUR_2", "10")
var cfg config
isNoErr(t, Parse(&cfg))
isEqual(t, time.Duration(cfg.Dur1), 20*time.Minute)
isEqual(t, time.Duration(cfg.Dur2), 10*time.Second)
} |
Yes I can or
Or parse my own type separately from the main struct and use ToDuration() and store in the struct, which is a bit awkward in my opinion And if I want to use it in combination with flag I have to implement And BTW the defaultTypeParsers from the var name hints to me that I should be able to use something custom if I want to :) |
|
yeah, you right. all right, let's merge this, but it'll be a breaking change. |
…Map keys (caarlos0#272) BREAKING CHANGE: behavior changed and now default parsers can be overwritten. Co-authored-by: danielvanderwel <d.d.van.der.wel@gmai.com>
This small fix/feature adds the ability to override default ParserFunc in Options{FuncMap} for ParseWithOptions
When it can be useful:
When for some reason you can't use default ParseDuration format but want to have a time.Duration
Like today I ran into a small but very annoying problem
I had some executions like
INTERVAL=1 ./script.shand wanted to override time.Duration parser but it was not possible.We may also want to override the URL parser or some other future defaultTypeParsers