ParseDuration Reads Config Durations
Parse duration strings like 300ms and 1h30m with time.ParseDuration, seeing which units it accepts, how it renders 90s, and why a bare number fails.
Code
package main
import (
"fmt"
"time"
)
// 配置里的超时值都是字符串:解析交给 ParseDuration
func parseTimeout(raw string) (time.Duration, error) {
d, err := time.ParseDuration(raw)
if err != nil {
return 0, fmt.Errorf("timeout %q: %w", raw, err)
}
return d, nil
}
func main() {
for _, raw := range []string{"300ms", "1h30m", "90s", "5", "-2m", ""} {
d, err := parseTimeout(raw)
fmt.Printf("%-8q -> %-10v err=%v
", raw, d, err)
}
// 合法值继续参与运算:加 10% 余量
deadline, _ := parseTimeout("1h30m")
fmt.Println("with headroom:", deadline+deadline/10)
}What the code does
Structurally, expect the functions parseTimeout and main and nothing else.
Iteration happens inside for _, raw := range []string{"300ms", "1h30m", "90s", "5", "-2m", ""} — everything outside it runs once. Failures are values here: 1 site check err and decide instead of letting one propagate.
Watch out for
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
Signature: func parseTimeout(raw string) (time.Duration, error)
Running the file prints labeled results such as with headroom: — each operation’s effect is visible in the output.
The sequence parseTimeout lives in main; running the file triggers it.
Key statements
return 0, fmt.Errorf("timeout %q: %w", raw, err)
for _, raw := range []string{"300ms", "1h30m", "90s", "5", "-2m", ""} {
d, err := parseTimeout(raw)
fmt.Printf("%-8q -> %-10v err=%v
", raw, d, err)
}
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- No exceptions — `error` returns checked at 1 site, and callers branch on `err` first.
- What does ParseDuration Reads Config Durations print when run?
- Execute the whole file; each printed line is prefixed with a label like `with headroom:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.