Fields of type time.Duration should fail when the input is an integer
arieltorti opened this issue · 1 comments
The duration parser provided by the standard library fails when it's input doesn't include a time unit. As expected, fig also fails in such a case, but it doesn't when the input is not wrapped in quotes because it's interpreted as an integer and not a string.
For example, given:
// config.yaml
timeout: 1
// main.go
package main
import (
"fmt"
"log"
"time"
"github.com/kkyr/fig"
)
type Config struct {
Timeout time.Duration `fig:"timeout" validate:"required"`
}
func main() {
var cfg Config
if err := fig.Load(&cfg); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", cfg)
}
I would expect it to fail because timeout: 1
doesn't have a time unit, instead the config is parsed without errors and the set value is 1ns.
Maybe this could be fixed by adding a check of Int (and maybe float?) values in StringToTimeDurationHookFunc
, although I may be missing some other cases.
time.Duration
is an alias to int64
and represents an elapsed time in nanoseconds, so converting an integer to a time.Duration
directly using a typecast, e.g. time.Duration(1000)
, is a valid use case.
I agree that it's not very intuitive to do so but it's not wrong, therefore I don't think parsing should fail when the input is an integer.