-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_api_request_test.go
76 lines (70 loc) · 1.36 KB
/
example_api_request_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
package jsmu_test
import (
"fmt"
"github.com/nofeaturesonlybugs/jsmu"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
type ApiGetPerson struct {
jsmu.TypeName `json:"-" jsmu:"get/person"`
//
Id int `json:"id"`
Person *Person `json:"person"`
}
func ExampleMU_apiRequest() {
//
people := map[int]*Person{
10: {
Name: "Bob",
Age: 40,
},
20: {
Name: "Sally",
Age: 32,
},
}
//
mu := &jsmu.MU{}
mu.MustRegister(&ApiGetPerson{})
//
strings := []string{
`{
"type" : "get/person",
"id" : "first",
"message" : {
"id" : 20
}
}`,
`{
"type" : "get/person",
"id" : "second",
"message" : {
"id" : 10
}
}`,
}
var envelope jsmu.Enveloper
var response []byte
var err error
for _, str := range strings {
if envelope, err = mu.Unmarshal([]byte(str)); err != nil {
fmt.Println(err)
return
}
switch message := envelope.GetMessage().(type) {
case *ApiGetPerson:
if person, ok := people[message.Id]; ok {
message.Person = person
}
}
if response, err = mu.Marshal(envelope); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%v\n", string(response))
}
// Output: {"type":"get/person","id":"first","message":{"id":20,"person":{"name":"Sally","age":32}}}
// {"type":"get/person","id":"second","message":{"id":10,"person":{"name":"Bob","age":40}}}
}