-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.go
87 lines (71 loc) · 1.77 KB
/
model.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package krud
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"unicode"
)
// Date is borrowed from:
// https://stackoverflow.com/questions/45303326/how-to-parse-non-standard-time-format-from-json
// Overrides time.Time with only year, month, day in JSON representation.
type Date time.Time
// Implement Marshaler and Unmarshaler interface
func (d *Date) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), "\"")
t, err := time.Parse("2006-01-02", s)
if err != nil {
return err
}
*d = Date(t)
return nil
}
func (d Date) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Time(d).Format("2006-01-02"))
}
// Maybe a Format function for printing your date
func (d Date) Format(s string) string {
t := time.Time(d)
return t.Format(s)
}
type Author struct {
ID int64 `json:"id"`
Name string `json:"name"`
DateOfBirth Date `json:"dateofbirth"`
}
// Validate does basic sanity checking of this Author.
// But there is always:
// https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/
func (a *Author) Validate() error {
if len(a.Name) == 0 {
return errors.New("name empty")
}
for _, r := range a.Name {
if unicode.IsLetter(r) {
continue
}
if r == ' ' || r == '.' {
continue
}
return fmt.Errorf("name contains unexpected rune: %c", r)
}
if time.Time(a.DateOfBirth).IsZero() {
return errors.New("birthdate before the start of civilization")
}
return nil
}
type Book struct {
ID int64 `json:"id"`
Title string `json:"title"`
Published Date `json:"published"`
}
func (b *Book) Validate() error {
if len(b.Title) == 0 {
return errors.New("title empty")
}
if time.Time(b.Published).IsZero() {
return errors.New("published before the start of civilization")
}
return nil
}