-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjson.go
42 lines (36 loc) · 924 Bytes
/
json.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
// SPDX-FileCopyrightText: Winni Neessen <[email protected]> et al
//
// SPDX-License-Identifier: MIT
package hibp
import (
"errors"
"fmt"
"strings"
"time"
)
// APIDate is type wrapper for datestamp (without time) returned by the HIBP API
type APIDate struct {
time.Time
}
// UnmarshalJSON for the APIDate type converts a give date string into a time.Time type
func (a *APIDate) UnmarshalJSON(p []byte) error {
input := strings.ReplaceAll(string(p), `"`, ``)
if input == "null" || input == "" {
return nil
}
var parsed time.Time
var err error
switch len(input) {
case 10:
parsed, err = time.Parse("2006-01-02", input)
case 19:
parsed, err = time.Parse("2006-01-02T15:04:05", input)
default:
return errors.New("failed to parse JSON string as API date: unknown date format")
}
if err != nil {
return fmt.Errorf("failed to parse JSON string as API date: %w", err)
}
a.Time = parsed
return nil
}