Skip to content

Commit

Permalink
feat(sources/env): add Duration method
Browse files Browse the repository at this point in the history
  • Loading branch information
qdm12 committed Jun 9, 2023
1 parent 8b27587 commit c601cb7
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions sources/env/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,26 @@ func (e *Env) DurationPtr(envKey string, options ...Option) (

return durationPtr, nil
}

// Duration returns a `time.Duration` from an environment
// variable value.
// If the environment variable is not set or its value is
// the empty string, `0` is returned.
// Otherwise, if the value is not a valid duration string,
// an error is returned with the environment variable name
// in the error context.
func (e *Env) Duration(envKey string, options ...Option) (
duration time.Duration, err error) {
s := e.Get(envKey, options...)
if s == nil || *s == "" {
// note: no point accepting the empty string in this case
return 0, nil
}

duration, err = time.ParseDuration(*s)
if err != nil {
return 0, fmt.Errorf("environment variable %s: %w", envKey, err)
}

return duration, nil
}

0 comments on commit c601cb7

Please sign in to comment.