-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples_test.go
156 lines (146 loc) · 2.54 KB
/
examples_test.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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package jsonmsg
import (
"encoding/json"
"fmt"
)
// Parse a schema into an Index of Schemas
func ExampleParse() {
schema := `
{
"endpoints": {
"http": "https://jsonmsg.github.io/v1",
"websocket": "wss://jsonmsg.github.io/v1"
},
"messages": {
"findUser": {
"in": "#/definitions/userQuery",
"outs": [
"#/definitions/user",
"#/definitions/error"
],
"group": "user"
}
},
"definitions": {
"user": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
}
},
"required": ["id", "name"]
},
"userQuery": {
"type": "object",
"properties": {
"id": {
"type": "string"
}
},
"required": ["id"]
},
"error": {
"type": "object",
"properties": {
"message": {
"type": "string"
}
},
"required": ["message"]
}
}
}
`
// parse into index
spec, err := Parse([]byte(schema))
if err != nil {
panic(err)
}
fmt.Printf("findUser name: %s\n", spec.Messages["findUser"].Name)
fmt.Printf("findUser in name: %s\n", spec.Messages["findUser"].InSchema.Name)
fmt.Printf("findUser in group: %s\n", spec.GroupedMessages["user"]["findUser"].InSchema.Name)
// Output:
// findUser name: FindUser
// findUser in name: UserQuery
// findUser in group: UserQuery
}
// Generate a sample message conforming to the specified message schema
func ExampleMessage_NewInstance() {
schema := `
{
"endpoints": {
"http": "https://jsonmsg.github.io/v1",
"websocket": "wss://jsonmsg.github.io/v1"
},
"messages": {
"findUser": {
"in": "#/definitions/userQuery",
"outs": [
"#/definitions/user",
"#/definitions/error"
],
"group": "user"
}
},
"definitions": {
"user": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
}
},
"required": ["id", "name"]
},
"userQuery": {
"type": "object",
"properties": {
"id": {
"type": "string"
}
},
"required": ["id"]
},
"error": {
"type": "object",
"properties": {
"message": {
"type": "string"
}
},
"required": ["message"]
}
}
}
`
// parse into spec
spec, err := Parse([]byte(schema))
if err != nil {
panic(err)
}
// create go instance
inst, err := spec.Messages["findUser"].NewInstance()
if err != nil {
panic(err)
}
// marshal to json
raw, err := json.MarshalIndent(inst, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", raw)
// Output:
// {
// "data": {
// "id": "string"
// },
// "msg": "findUser"
// }
}