2021-09-26 21:06:40 +00:00
|
|
|
package conf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// StringDuration is a duration that is unmarshaled from a string.
|
|
|
|
// Durations are normally unmarshaled from numbers.
|
|
|
|
type StringDuration time.Duration
|
|
|
|
|
2022-06-21 11:41:15 +00:00
|
|
|
// MarshalJSON implements json.Marshaler.
|
2021-09-26 21:06:40 +00:00
|
|
|
func (d StringDuration) MarshalJSON() ([]byte, error) {
|
|
|
|
return json.Marshal(time.Duration(d).String())
|
|
|
|
}
|
|
|
|
|
2022-06-21 11:41:15 +00:00
|
|
|
// UnmarshalJSON implements json.Unmarshaler.
|
2021-09-26 21:06:40 +00:00
|
|
|
func (d *StringDuration) UnmarshalJSON(b []byte) error {
|
2021-09-27 08:36:28 +00:00
|
|
|
var in string
|
|
|
|
if err := json.Unmarshal(b, &in); err != nil {
|
2021-09-26 21:06:40 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-09-27 08:36:28 +00:00
|
|
|
du, err := time.ParseDuration(in)
|
2021-09-26 21:06:40 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
*d = StringDuration(du)
|
2021-09-27 08:36:28 +00:00
|
|
|
|
2021-09-26 21:06:40 +00:00
|
|
|
return nil
|
|
|
|
}
|
2021-10-11 09:46:40 +00:00
|
|
|
|
2023-05-06 21:00:42 +00:00
|
|
|
// UnmarshalEnv implements envUnmarshaler.
|
|
|
|
func (d *StringDuration) UnmarshalEnv(s string) error {
|
2021-10-11 09:46:40 +00:00
|
|
|
return d.UnmarshalJSON([]byte(`"` + s + `"`))
|
|
|
|
}
|