forked from pgaskin/BookBrowser
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathparser.go
More file actions
45 lines (39 loc) · 1004 Bytes
/
parser.go
File metadata and controls
45 lines (39 loc) · 1004 Bytes
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
package main
import (
"fmt"
"reflect"
"strings"
"time"
"github.com/araddon/dateparse"
"github.com/mitchellh/mapstructure"
)
// ParseTime will parse an arbitrary date string and try to create a time.Time.
func ParseTime(date string) (time.Time, error) {
if strings.TrimSpace(date) == "" {
return time.Unix(0, 0), nil
}
return dateparse.ParseAny(date)
}
func parseResult(input interface{}) (*Book, error) {
var out Book
config := mapstructure.DecoderConfig{
DecodeHook: func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if t == reflect.TypeOf(time.Time{}) && f == reflect.TypeOf("") {
return ParseTime(data.(string))
}
return data, nil
},
Result: &out,
}
decoder, err := mapstructure.NewDecoder(&config)
if err != nil {
return nil, fmt.Errorf("creating decoder failed with error %w", err)
}
if err := decoder.Decode(input); err != nil {
return nil, fmt.Errorf("decoding failed with error %w", err)
}
return &out, nil
}