/
session.go
61 lines (49 loc) · 1.32 KB
/
session.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
package model
import (
"encoding/json"
"errors"
"time"
)
// ErrSessionNotFound is when session not found.
var ErrSessionNotFound = errors.New("Session not found. ")
// Session is a session.
type Session struct {
ID string `json:"id"`
ExpirationTime int64 `json:"expiration_time"`
}
// SessionDuration wraps time.Duration to implement custom yaml and json encoding and decoding.
type SessionDuration struct {
time.Duration
}
// MarshalJSON implements json.Marshaller.
func (sd SessionDuration) MarshalJSON() ([]byte, error) {
return json.Marshal(sd.Duration / time.Second)
}
// UnmarshalJSON implements json.Unmarshaller.
func (sd *SessionDuration) UnmarshalJSON(data []byte) error {
if sd == nil {
return nil
}
var aux int
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
sd.Duration = time.Second * time.Duration(aux)
return nil
}
// MarshalYAML implements yaml.Marshaller.
func (sd SessionDuration) MarshalYAML() (interface{}, error) {
return int(sd.Duration / time.Second), nil
}
// UnmarshalYAML implements yaml Unmarshaller.
func (sd *SessionDuration) UnmarshalYAML(unmarshal func(interface{}) error) error {
if sd == nil {
return nil
}
var aux int
if err := unmarshal(&aux); err != nil {
return err
}
*sd = SessionDuration{Duration: time.Second * time.Duration(aux)}
return nil
}