-
Notifications
You must be signed in to change notification settings - Fork 46
/
numeric_date.go
43 lines (38 loc) · 979 Bytes
/
numeric_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
package jwt
import (
"encoding/json"
"math"
"strconv"
"time"
)
// NumericDate represents date for StandardClaims
// See: https://tools.ietf.org/html/rfc7519#section-2
type NumericDate struct {
time.Time
}
// NewNumericDate creates a new NumericDate value from time.Time.
func NewNumericDate(t time.Time) *NumericDate {
return &NumericDate{t}
}
// MarshalJSON implements the json.Marshaler interface.
func (t NumericDate) MarshalJSON() ([]byte, error) {
if t.IsZero() {
return []byte("null"), nil
}
return []byte(strconv.FormatInt(t.Unix(), 10)), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (t *NumericDate) UnmarshalJSON(data []byte) error {
var value json.Number
if err := json.Unmarshal(data, &value); err != nil {
return ErrDateInvalidFormat
}
f, err := value.Float64()
if err != nil {
return ErrDateInvalidFormat
}
sec, dec := math.Modf(f)
ts := time.Unix(int64(sec), int64(dec*1e9))
*t = NumericDate{ts}
return nil
}