util: add parse fallback helpers (#20022)

util/def: add def.Bool and def.Duration default parse helpers

Replace multiple instances of def.Bool and def.Duration with a new util/def
package.

Updates #20018

Co-authored-by: Bobby <boby@codelabs.co.id>
Co-authored-by: Simon Law <sfllaw@tailscale.com>
Signed-off-by: Bobby <boby@codelabs.co.id>
Signed-off-by: Simon Law <sfllaw@tailscale.com>
This commit is contained in:
Bobi Gunardi
2026-06-15 15:58:51 -07:00
committed by GitHub
co-authored by Bobby Simon Law
parent 94fbb03352
commit ca20611d11
11 changed files with 170 additions and 52 deletions
+34
View File
@@ -0,0 +1,34 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// Package def parses strings with fallback default values.
package def
import (
"strconv"
"time"
)
// Bool parses s as a bool, returning def when s is empty or invalid.
func Bool(s string, def bool) bool {
if s == "" {
return def
}
v, err := strconv.ParseBool(s)
if err != nil {
return def
}
return v
}
// Duration parses s as a time.Duration, returning def when s is empty or invalid.
func Duration(s string, def time.Duration) time.Duration {
if s == "" {
return def
}
v, err := time.ParseDuration(s)
if err != nil {
return def
}
return v
}