Go: Validate timeout bounds after parsing a duration
A duration can parse successfully and still be unsuitable as a timeout. Apply the service’s bounds after time.ParseDuration; this example accepts values greater than zero and no more than five seconds.
Set up
Tested on Linux with Go 1.26.10. Use Bash with Go on your PATH. Keep the same terminal through cleanup, and stop if setup fails.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as parse_duration_timeout_bounds.go:
package main
import (
"fmt"
"time"
)
func main() {
for _, input := range []string{"250ms", "1.5s", "5s", "6s", "0", "-1s", "2d", "500"} {
d, err := time.ParseDuration(input)
if err != nil {
fmt.Printf("%q: rejected syntax\n", input)
continue
}
if d <= 0 || d > 5*time.Second {
fmt.Printf("%q: rejected policy\n", input)
continue
}
fmt.Printf("%q: accepted %s\n", input, d)
}
}go run parse_duration_timeout_bounds.goObserved output:
"250ms": accepted 250ms
"1.5s": accepted 1.5s
"5s": accepted 5s
"6s": rejected policy
"0": rejected policy
"-1s": rejected policy
"2d": rejected syntax
"500": rejected syntaxRead the result
Fractional seconds are valid. Zero and negative durations also parse, but fail this policy. The parser does not accept a day suffix, and a nonzero number without a unit is invalid. The special string 0 explains why syntax validation alone cannot enforce a positive timeout.
Apply it carefully
Five seconds is an example application limit, not a recommended timeout for every operation. Parsing does not start a timer or enforce a deadline. Wire the validated duration into the appropriate context or client configuration, and check how that API treats zero.
See the Go standard-library reference.
Clean up
Remove the source and the empty scratch directory. Go may retain build-cache files outside this directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- parse_duration_timeout_bounds.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.