-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeep_example_test.go
76 lines (68 loc) · 1.84 KB
/
meep_example_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 meep_test
import (
"encoding/json"
"fmt"
"."
)
func ExampleSigh() {
type Envelope struct {
Protocol string
MsgType string
Msg interface{}
}
type AppleMsg struct{ Opacity int }
type PearMsg struct{ Cambre string }
type ErrBadProtocolHandshake struct {
meep.TraitCausable
meep.TraitAutodescribing
}
type ErrMalformedMessage struct {
meep.TraitCausable
meep.TraitAutodescribing
ExpectedType string
}
envelopeRaw := []byte(`{"Protocol":"7", "MsgType":"apple", "Msg":{"Opacity":"stringy"}}`)
_, err := func() (*Envelope, error) {
msgRaw := json.RawMessage{}
msgEnvelope := &Envelope{Msg: &msgRaw}
if err := json.Unmarshal(envelopeRaw, msgEnvelope); err != nil {
return nil, meep.New(
&ErrBadProtocolHandshake{},
meep.Cause(err),
)
}
var msg interface{}
switch msgEnvelope.MsgType {
case "apple":
msg = &AppleMsg{}
case "pear":
msg = &PearMsg{}
default:
return msgEnvelope, meep.New(
&ErrBadProtocolHandshake{},
meep.Cause(fmt.Errorf("unknown message type")),
)
}
if err := json.Unmarshal(msgRaw, msg); err != nil {
return msgEnvelope, meep.New(
&ErrMalformedMessage{ExpectedType: msgEnvelope.MsgType},
meep.Cause(fmt.Errorf("json: cannot unmarshal")),
// ...sorry, this is not a great example.
// We used to have this take the actually 'err' returned
// and pass that on as cause, which makes much more sense.
// However, the strings returned by stdlib's json.Unmarshal
// function have changed across go versions, which caused
// this test to fail on some go versions, so we had to
// flatten it. Versioning! It's important.
)
}
msgEnvelope.Msg = msg
return msgEnvelope, nil
}()
fmt.Printf("%s\n", err)
// Output:
//
// Error[meep_test.ErrMalformedMessage]: ExpectedType="apple";
// Caused by: json: cannot unmarshal
//
}