From faac09ac0c2cf21243f96d15d9e9db45734feb57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ask=20Bj=C3=B8rn=20Hansen?= Date: Fri, 6 Jun 2025 19:08:16 -0700 Subject: [PATCH] timeutil: Add documentation --- timeutil/duration.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/timeutil/duration.go b/timeutil/duration.go index 458092a..9aa63b0 100644 --- a/timeutil/duration.go +++ b/timeutil/duration.go @@ -1,3 +1,4 @@ +// Package timeutil provides JSON-serializable time utilities. package timeutil import ( @@ -6,14 +7,37 @@ import ( "time" ) +// Duration is a wrapper around time.Duration that supports JSON marshaling/unmarshaling. +// +// When marshaling to JSON, it outputs the duration as a string using time.Duration.String(). +// When unmarshaling from JSON, it accepts both: +// - String values that can be parsed by time.ParseDuration (e.g., "30s", "5m", "1h30m") +// - Numeric values that represent nanoseconds as a float64 +// +// This makes it compatible with configuration files and APIs that need to represent +// durations in a human-readable format. +// +// Example usage: +// +// type Config struct { +// Timeout timeutil.Duration `json:"timeout"` +// } +// +// // JSON: {"timeout": "30s"} +// // or: {"timeout": 30000000000} type Duration struct { time.Duration } +// MarshalJSON implements json.Marshaler. +// It marshals the duration as a string using time.Duration.String(). func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(time.Duration(d.Duration).String()) } +// UnmarshalJSON implements json.Unmarshaler. +// It accepts both string values (parsed via time.ParseDuration) and +// numeric values (interpreted as nanoseconds). func (d *Duration) UnmarshalJSON(b []byte) error { var v any if err := json.Unmarshal(b, &v); err != nil {