-
Notifications
You must be signed in to change notification settings - Fork 1
/
codec_time.go
46 lines (40 loc) · 887 Bytes
/
codec_time.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
package forms
import (
"fmt"
"time"
)
// TimeCodec is a codec for time.Time values
type TimeCodec struct {
format string
}
var _ Codec = &TimeCodec{}
func NewTimeCodec(format string) Codec {
return &TimeCodec{format: format}
}
// Encode implements Encoder.Encode
func (c *TimeCodec) Encode(value interface{}) (string, error) {
switch v := value.(type) {
case *time.Time:
if v == nil {
return "", nil
}
return v.Format(c.format), nil
case time.Time:
if (v == time.Time{}) || v.IsZero() {
return "", nil
}
return v.Format(c.format), nil
}
return "", fmt.Errorf("invalid value type")
}
// Decode implements Decoder.Decode
func (c *TimeCodec) Decode(value string) (interface{}, error) {
if value == "" {
return (*time.Time)(nil), nil
}
parsed, err := time.Parse(c.format, value)
if err != nil {
return (*time.Time)(nil), err
}
return parsed, nil
}