How does everyone feel about adding a function like this? This would allow numeric values to be converted into a time.Duration, even if they aren't represented in nanoseconds. For example, if a field is storing seconds as a float64 and you want to convert to a time.Duration.
Thoughts? If we get some positive feedback here, I'll open a PR.
Draft implementation might look like this:
// NumberToTimeDurationHookFunc returns a DecodeHookFuncType that multiplies a
// numeric value by the specified factor when it is to be decoded into a
// time.Duration. Example: `NumberToTimeDurationHookFunc(time.Second)` converts
// numeric values as seconds into a time.Duration.
func NumberToTimeDurationHookFunc(
factor time.Duration,
) mapstructure.DecodeHookFuncType {
return func(fromT reflect.Type, toT reflect.Type, data any) (any, error) {
if toT != timeDurationType || fromT == toT {
return data, nil
}
// Multiply data by `factor`
switch val := data.(type) {
case uint8:
return time.Duration(val) * factor, nil
case uint16:
return time.Duration(val) * factor, nil
case uint32:
return time.Duration(val) * factor, nil
case uint64:
return time.Duration(val) * factor, nil
case uint:
return time.Duration(val) * factor, nil
case int8:
return time.Duration(val) * factor, nil
case int16:
return time.Duration(val) * factor, nil
case int32:
return time.Duration(val) * factor, nil
case int64:
return time.Duration(val) * factor, nil
case int:
return time.Duration(val) * factor, nil
case float32:
return time.Duration(float64(val) * float64(factor)), nil
case float64:
return time.Duration(val * float64(factor)), nil
default:
return nil, fmt.Errorf(
"expected duration to be a number, got %T", data,
)
}
}
}
How does everyone feel about adding a function like this? This would allow numeric values to be converted into a time.Duration, even if they aren't represented in nanoseconds. For example, if a field is storing seconds as a
float64and you want to convert to atime.Duration.Thoughts? If we get some positive feedback here, I'll open a PR.
Draft implementation might look like this: