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
+2 -13
View File
@@ -11,7 +11,6 @@ import (
"net"
"net/http"
"net/netip"
"strconv"
"strings"
"sync"
"time"
@@ -20,6 +19,7 @@ import (
"tailscale.com/net/netmon"
"tailscale.com/net/portmapper"
"tailscale.com/types/logger"
"tailscale.com/util/def"
"tailscale.com/util/eventbus"
)
@@ -66,7 +66,7 @@ func serveDebugPortmap(h *localapi.Handler, w http.ResponseWriter, r *http.Reque
}
}
if defBool(r.FormValue("log_http"), false) {
if def.Bool(r.FormValue("log_http"), false) {
debugKnobs.LogHTTP = true
}
@@ -191,14 +191,3 @@ func serveDebugPortmap(h *localapi.Handler, w http.ResponseWriter, r *http.Reque
}
}
}
func defBool(a string, def bool) bool {
if a == "" {
return def
}
v, err := strconv.ParseBool(a)
if err != nil {
return def
}
return v
}
+3 -25
View File
@@ -5,7 +5,6 @@ package routecheck
import (
"net/http"
"strconv"
"time"
jsonv2 "github.com/go-json-experiment/json"
@@ -13,6 +12,7 @@ import (
"tailscale.com/ipn/localapi"
"tailscale.com/net/routecheck"
"tailscale.com/util/def"
"tailscale.com/util/httpm"
)
@@ -39,8 +39,8 @@ func serveRouteCheck(h *localapi.Handler, w http.ResponseWriter, r *http.Request
var err error
var report *routecheck.Report
if defBool(r.FormValue("probe"), false) {
timeout := defDuration(r.FormValue("timeout"), routecheck.DefaultTimeout)
if def.Bool(r.FormValue("probe"), false) {
timeout := def.Duration(r.FormValue("timeout"), routecheck.DefaultTimeout)
timeout = min(max(0, timeout), 60*time.Second) // clamp to [0s, 60s]
report, err = rc.Refresh(r.Context(), timeout)
} else {
@@ -61,25 +61,3 @@ func serveRouteCheck(h *localapi.Handler, w http.ResponseWriter, r *http.Request
// with its default options, marshal with DefaultOptionsV1.
jsonv2.MarshalWrite(w, report, jsonv1.DefaultOptionsV1())
}
func defBool(a string, def bool) bool {
if a == "" {
return def
}
v, err := strconv.ParseBool(a)
if err != nil {
return def
}
return v
}
func defDuration(a string, def time.Duration) time.Duration {
if a == "" {
return def
}
v, err := time.ParseDuration(a)
if err != nil {
return def
}
return v
}