-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
118 lines (101 loc) · 2.19 KB
/
main.go
File metadata and controls
118 lines (101 loc) · 2.19 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"fmt"
"log"
"github.com/metafates/schema/examples/parse-grpc/pb"
"github.com/metafates/schema/optional"
"github.com/metafates/schema/parse"
"github.com/metafates/schema/required"
)
type AddressBook struct {
People []Person
}
type Person struct {
Name required.NonZero[string]
Id required.Positive0[int32]
Email optional.Email[string]
Phones []PhoneNumber
}
type PhoneType int
const (
PhoneTypeMobile = iota
PhoneTypeHome
PhoneTypeWork
)
type PhoneNumber struct {
Type optional.Any[PhoneType]
Number required.NonZero[string]
}
func main() {
options := []parse.Option{
parse.WithDisallowUnknownFields(),
}
// let's parse valid address book from grpc
{
var book AddressBook
err := parse.Parse(pb.AddressBook{
People: []*pb.Person{
{
Name: "Example Name",
Id: 12345,
Email: "name@example.com",
Phones: []*pb.Person_PhoneNumber{
{
Number: "123-456-7890",
Type: pb.Person_HOME,
},
{
Number: "222-222-2222",
Type: pb.Person_MOBILE,
},
{
Number: "111-111-1111",
Type: pb.Person_WORK,
},
},
},
},
}, &book, options...)
if err != nil {
log.Fatalln(err)
}
fmt.Printf("book.People: %v\n", len(book.People))
// 1
fmt.Printf("book.People[0].Name: %v\n", book.People[0].Name.Get())
// Example Name
fmt.Printf("book.People[0].Phones: %v\n", len(book.People[0].Phones))
// 3
fmt.Printf(
"pb.Person_MOBILE == PhoneTypeMobile = %v\n",
book.People[0].Phones[1].Type.Must() == PhoneTypeMobile,
)
// pb.Person_MOBILE == PhoneTypeMobile = true
}
// now let's try to trigger error by violating the schema
{
var book AddressBook
err := parse.Parse(pb.AddressBook{
People: []*pb.Person{
{
Name: "Example Name",
Id: 12345,
Email: "not a valid email",
Phones: []*pb.Person_PhoneNumber{
{
Number: "123-456-7890",
Type: pb.Person_HOME,
},
{
Type: pb.Person_MOBILE,
},
{
Number: "111-111-1111",
Type: pb.Person_WORK,
},
},
},
},
}, &book, options...)
fmt.Println(err) // [0].Email: mail: no angle-addr
}
}