-
Notifications
You must be signed in to change notification settings - Fork 5
/
noop.go
119 lines (103 loc) · 1.74 KB
/
noop.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
package codec
import (
"encoding/json"
"io"
)
type noopCodec struct{}
func (c *noopCodec) ReadHeader(conn io.Reader, m *Message, t MessageType) error {
return nil
}
func (c *noopCodec) ReadBody(conn io.Reader, b interface{}) error {
// read bytes
buf, err := io.ReadAll(conn)
if err != nil {
return err
}
if b == nil {
return nil
}
switch v := b.(type) {
case *string:
*v = string(buf)
case *[]byte:
*v = buf
case *Frame:
v.Data = buf
default:
return json.Unmarshal(buf, v)
}
return nil
}
func (c *noopCodec) Write(conn io.Writer, m *Message, b interface{}) error {
if b == nil {
return nil
}
var v []byte
switch vb := b.(type) {
case *Frame:
v = vb.Data
case string:
v = []byte(vb)
case *string:
v = []byte(*vb)
case *[]byte:
v = *vb
case []byte:
v = vb
default:
var err error
v, err = json.Marshal(vb)
if err != nil {
return err
}
}
_, err := conn.Write(v)
return err
}
func (c *noopCodec) String() string {
return "noop"
}
// NewCodec returns new noop codec
func NewCodec() Codec {
return &noopCodec{}
}
func (c *noopCodec) Marshal(v interface{}) ([]byte, error) {
if v == nil {
return nil, nil
}
switch ve := v.(type) {
case string:
return []byte(ve), nil
case *string:
return []byte(*ve), nil
case *[]byte:
return *ve, nil
case []byte:
return ve, nil
case *Frame:
return ve.Data, nil
case *Message:
return ve.Body, nil
}
return json.Marshal(v)
}
func (c *noopCodec) Unmarshal(d []byte, v interface{}) error {
if v == nil {
return nil
}
switch ve := v.(type) {
case *string:
*ve = string(d)
return nil
case *[]byte:
*ve = d
return nil
case *Frame:
ve.Data = d
return nil
case *Message:
ve.Body = d
return nil
}
return json.Unmarshal(d, v)
}