112 lines
2.1 KiB
Go
112 lines
2.1 KiB
Go
package shared
|
|
|
|
import (
|
|
"encoding/json"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type FlexibleTime time.Time
|
|
|
|
func (t FlexibleTime) Time() time.Time { return time.Time(t) }
|
|
|
|
func (t FlexibleTime) IsZero() bool { return time.Time(t).IsZero() }
|
|
|
|
func (t FlexibleTime) MarshalJSON() ([]byte, error) {
|
|
return time.Time(t).MarshalJSON()
|
|
}
|
|
|
|
func (t *FlexibleTime) UnmarshalJSON(b []byte) error {
|
|
*t = FlexibleTime{}
|
|
raw := strings.TrimSpace(string(b))
|
|
if raw == "" || raw == "null" {
|
|
return nil
|
|
}
|
|
|
|
var n json.Number
|
|
if err := json.Unmarshal(b, &n); err == nil {
|
|
s := n.String()
|
|
if parsed, ok := parseFlexibleTime(s); ok {
|
|
*t = parsed
|
|
return nil
|
|
}
|
|
if unix, err := n.Int64(); err == nil && unix > 0 {
|
|
*t = FlexibleTime(time.Unix(unix, 0).UTC())
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var s string
|
|
if err := json.Unmarshal(b, &s); err != nil {
|
|
return nil
|
|
}
|
|
if parsed, ok := parseFlexibleTime(s); ok {
|
|
*t = parsed
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func parseFlexibleTime(s string) (FlexibleTime, bool) {
|
|
s = strings.TrimSpace(s)
|
|
if s == "" {
|
|
return FlexibleTime{}, false
|
|
}
|
|
switch strings.ToLower(s) {
|
|
case "string", "undefined", "null", "none", "invalid", "nan", "-":
|
|
return FlexibleTime{}, false
|
|
}
|
|
for _, layout := range []string{
|
|
time.RFC3339Nano,
|
|
time.RFC3339,
|
|
"2006-01-02T15:04:05Z07:00",
|
|
"2006-01-02T15:04:05.000Z",
|
|
"2006-01-02T15:04:05",
|
|
"2006-01-02 15:04:05",
|
|
"2006-01-02",
|
|
"02.01.2006",
|
|
"02/01/2006",
|
|
"02-01-2006",
|
|
"2006/01/02",
|
|
"20060102",
|
|
} {
|
|
if parsed, err := time.Parse(layout, s); err == nil {
|
|
return FlexibleTime(parsed), true
|
|
}
|
|
}
|
|
return FlexibleTime{}, false
|
|
}
|
|
|
|
type FlexibleInt64 int64
|
|
|
|
func (n FlexibleInt64) Int64() int64 { return int64(n) }
|
|
|
|
func (n *FlexibleInt64) UnmarshalJSON(b []byte) error {
|
|
if string(b) == "null" {
|
|
*n = 0
|
|
return nil
|
|
}
|
|
|
|
var v int64
|
|
if err := json.Unmarshal(b, &v); err == nil {
|
|
*n = FlexibleInt64(v)
|
|
return nil
|
|
}
|
|
|
|
var s string
|
|
if err := json.Unmarshal(b, &s); err != nil {
|
|
return err
|
|
}
|
|
s = strings.TrimSpace(s)
|
|
if s == "" {
|
|
*n = 0
|
|
return nil
|
|
}
|
|
v, err := strconv.ParseInt(s, 10, 64)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
*n = FlexibleInt64(v)
|
|
return nil
|
|
}
|