tstime: add GoDuration which JSON serializes with time.Duration.String (#15726)

The encoding/json/v2 effort may end up changing
the default represention of time.Duration in JSON.
See https://go.dev/issue/71631

The GoDuration type allows us to explicitly use
the time.Duration.String representation regardless of
whether we serialize with v1 or v2 of encoding/json.

Updates tailscale/corp#27502

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
This commit is contained in:
Joe Tsai
2025-04-17 15:51:41 -07:00
committed by GitHub
parent 898cf06898
commit aff8f1b358
2 changed files with 55 additions and 0 deletions

View File

@@ -4,8 +4,11 @@
package tstime
import (
"encoding/json"
"testing"
"time"
"tailscale.com/util/must"
)
func TestParseDuration(t *testing.T) {
@@ -34,3 +37,17 @@ func TestParseDuration(t *testing.T) {
}
}
}
func TestGoDuration(t *testing.T) {
wantDur := GoDuration{time.Hour + time.Minute + time.Second + time.Millisecond + time.Microsecond + time.Nanosecond}
gotJSON := string(must.Get(json.Marshal(wantDur)))
wantJSON := `"1h1m1.001001001s"`
if gotJSON != wantJSON {
t.Errorf("json.Marshal(%v) = %s, want %s", wantDur, gotJSON, wantJSON)
}
var gotDur GoDuration
must.Do(json.Unmarshal([]byte(wantJSON), &gotDur))
if gotDur != wantDur {
t.Errorf("json.Unmarshal(%s) = %v, want %v", wantJSON, gotDur, wantDur)
}
}