-
-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: Parse number Durations in config correctly (fix #221)
This error edge case was introduced by #218.
- Loading branch information
1 parent
3f7b4c4
commit 59afe39
Showing
2 changed files
with
42 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package configutil | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"time" | ||
) | ||
|
||
// Duration is a configuration duration. | ||
// It is a wrapper around time.Duration that implements the json.Marshaler and json.Unmarshaler interfaces. | ||
// | ||
// - string is parsed using time.ParseDuration. | ||
// - int64 and float64 are interpreted as seconds. | ||
type Duration time.Duration | ||
|
||
func (d *Duration) MarshalJSON() ([]byte, error) { | ||
return json.Marshal(time.Duration(*d).String()) | ||
} | ||
|
||
func (d *Duration) UnmarshalJSON(data []byte) error { | ||
var a any | ||
if err := json.Unmarshal(data, &a); err != nil { | ||
return err | ||
} | ||
switch v := a.(type) { | ||
case string: | ||
dur, err := time.ParseDuration(v) | ||
if err != nil { | ||
return err | ||
} | ||
*d = Duration(dur) | ||
case float64: | ||
*d = Duration(time.Duration(v) * time.Second) | ||
case int64: | ||
*d = Duration(time.Duration(v) * time.Second) | ||
default: | ||
return fmt.Errorf("invalid duration type %T: %v", v, v) | ||
} | ||
return nil | ||
} |