/
expiration_date.go
64 lines (51 loc) · 1.31 KB
/
expiration_date.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
56
57
58
59
60
61
62
63
64
package quota_management
import (
"encoding/json"
"gopkg.in/yaml.v2"
"strings"
"time"
)
const layout = "2006-01-02 -07:00"
var _ json.Marshaler = &ExpirationDate{}
var _ json.Unmarshaler = &ExpirationDate{}
var _ yaml.Marshaler = &ExpirationDate{}
var _ yaml.Unmarshaler = &ExpirationDate{}
type ExpirationDate time.Time
func (e *ExpirationDate) UnmarshalJSON(b []byte) error {
value := strings.Trim(string(b), `"`) //get rid of "
if value == "" || value == "null" {
return nil
}
t, err := time.Parse(layout, value) //parse time
if err != nil {
return err
}
*e = ExpirationDate(t) //set result using the pointer
return nil
}
func (e *ExpirationDate) MarshalJSON() ([]byte, error) {
return []byte(`"` + time.Time(*e).Format(layout) + `"`), nil
}
func (e *ExpirationDate) MarshalYAML() (any, error) {
return time.Time(*e).Format(layout), nil
}
func (e *ExpirationDate) UnmarshalYAML(unmarshal func(any) error) error {
var buf string
err := unmarshal(&buf)
if err != nil {
return err
}
t, err := time.Parse(layout, buf) //parse time
if err != nil {
return err
}
*e = ExpirationDate(t) //set result using the pointer
return nil
}
func (e *ExpirationDate) HasExpired() bool {
if e == nil {
// a nil expiration date means 'never expire'
return false
}
return time.Now().After(time.Time(*e))
}