-
Notifications
You must be signed in to change notification settings - Fork 14
/
doc.go
55 lines (43 loc) · 1.57 KB
/
doc.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
52
53
54
55
/*
Package jsontime gives simple marshalling directly to and from time objects
This is a simple package that provides wrapper types for time.Time and time.Duration
that can be marshalled to and from json and yaml.
time.Time already can marshal to and from json, but not yaml. Whereas
time.Duration cannot marshal to and from either. These wrapper types fill in
this gap.
This is extremely helpful for configuration and REST apis communicating via
json. For example
Unmarshalling yaml config:
type Config struct {
StartTime jsontime.StartTime `yaml:"startTime"`
RotationPeriod jsontime.Duration `yaml:"retryPeriod"`
}
var config Config
if err := yaml.Unmarshal(responseBodybody, &config); err != nil {
return err
}
// Get the actual time objects, not the jsontime type aliases
startTime := target.StartTime.Time()
rotationPeriod := target.RotationPeriod.Duration()
Unmarshalling a response:
type ResponseType struct {
RetryPeriod jsontime.Duration `json:"retryPeriod"`
}
var target ResponseType
if err := json.Unmarshal(responseBody, &target); err != nil {
// Error captures any parse error on the retryPeriod value
// rather than having to do that error check yourself
return err
}
retryPeriod := target.RetryPeriod.Duration()
Marshalling a json request/response:
type RequestBody struct {
RefreshRate jsontime.Duration `json:"refreshRate"`
}
requestBody := RequestBody{
RefreshRate: jsontime.Duration(2 * time.Minute),
}
marshalled, _ := json.Marshal(requestBody)
resp, err := http.Do(url, method, bytes.NewBuffer(marshalled))
*/
package jsontime