-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduration.go
More file actions
24 lines (19 loc) · 727 Bytes
/
duration.go
File metadata and controls
24 lines (19 loc) · 727 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package jsonutil
import (
"encoding/json/jsontext"
"encoding/json/v2"
"time"
)
// DurationMarshalIntSeconds is a custom marshaler for time.Duration, marshaling them as integers representing seconds.
func DurationMarshalIntSeconds(enc *jsontext.Encoder, d time.Duration) error {
return enc.WriteToken(jsontext.Int(int64(d / time.Second)))
}
// DurationUnmarshalIntSeconds is a custom unmarshaler for time.Duration, unmarshaling them from integers and assuming they represent seconds.
func DurationUnmarshalIntSeconds(dec *jsontext.Decoder, d *time.Duration) error {
var seconds int64
if err := json.UnmarshalDecode(dec, &seconds); err != nil {
return err
}
*d = time.Duration(seconds) * time.Second
return nil
}