-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
51 lines (41 loc) · 1.39 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package chesscompubapi
import (
"encoding/json"
"strings"
"time"
)
// UnixSecondsTimestamp decodes Unix seconds timestamps in JSON documents.
type UnixSecondsTimestamp time.Time
// UnmarshalJSON unmarshals an integer representing Unix seconds into a time.Time.
func (t *UnixSecondsTimestamp) UnmarshalJSON(data []byte) error {
var raw int64
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
*t = UnixSecondsTimestamp(time.Unix(raw, 0))
return nil
}
// DurationInSeconds decodes durations in seconds in JSON documents.
type DurationInSeconds time.Duration
// UnmarshalJSON unmarshals an integer representing a duration in seconds into a time.Duration.
func (d *DurationInSeconds) UnmarshalJSON(data []byte) error {
var raw int64
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
*d = DurationInSeconds(time.Second * time.Duration(raw))
return nil
}
// StringFromPathSuffix decodes url paths in JSON documents where only the part after the last string is needed.
type StringFromPathSuffix string
// UnmarshalJSON extracts the part after the last slash from a path.
// For example, "path/to/some/id" would be unmarshaled as "id".
func (d *StringFromPathSuffix) UnmarshalJSON(data []byte) error {
var raw string
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
parts := strings.Split(raw, "/")
*d = StringFromPathSuffix(parts[len(parts)-1])
return nil
}