Gotcha with time.Time.Add()
Table of Contents
If you have ever used Go and have written backends with it, you might have come across code similar to below
func doSomething(w http.ResponseWriter, r *http.Request) {
var input struct {
// ...
ValidDays uint `json:"validDays"`
}
// read input ...
db.CreateResource(db.Resource{
// ...
ExpirationDate: time.Now().Add(time.Hour * 24 * time.Duration(input.ValidDays)).UTC(),
})
}
On a quick glance, it does not look like there’s anything wrong with this code. But say you later decide to allow unlimited time, in which case you might just send a large number like 365000 (1000 yrs) in the “validDays” field. In that case the expression time.Hour * 24 * time.Duration(time.ValidDays) actually overflows time.Duration which is an int64. The compiler can’t complain about this because it won’t know about input.ValidDays during compilation.
To avoid this early, use the below instead
time.Now().AddDate(0, 0, time.ValidDays)