forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
132 lines (102 loc) · 2.3 KB
/
codec.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
package msgpackrpc
import (
"errors"
"fmt"
"io"
"github.com/micro/go-micro/codec"
"github.com/tinylib/msgp/msgp"
)
type msgpackCodec struct {
rwc io.ReadWriteCloser
mt codec.MessageType
body bool
}
func (c *msgpackCodec) Close() error {
return c.rwc.Close()
}
func (c *msgpackCodec) String() string {
return "msgpack-rpc"
}
// ReadHeader reads the header from the wire.
func (c *msgpackCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error {
c.mt = mt
switch mt {
case codec.Request:
var h Request
if err := msgp.Decode(c.rwc, &h); err != nil {
return err
}
c.body = h.hasBody
m.Id = h.ID
m.Endpoint = h.Method
case codec.Response:
var h Response
if err := msgp.Decode(c.rwc, &h); err != nil {
return err
}
c.body = h.hasBody
m.Id = h.ID
m.Error = h.Error
case codec.Publication:
var h Notification
if err := msgp.Decode(c.rwc, &h); err != nil {
return err
}
c.body = h.hasBody
m.Endpoint = h.Method
default:
return errors.New("Unrecognized message type")
}
return nil
}
// ReadBody reads the body of the message. It is assumed the value being
// decoded into is a satisfies the msgp.Decodable interface.
func (c *msgpackCodec) ReadBody(v interface{}) error {
if !c.body {
return nil
}
r := msgp.NewReader(c.rwc)
// Body is present, but no value to decode into.
if v == nil {
return r.Skip()
}
switch c.mt {
case codec.Request, codec.Response, codec.Publication:
return decodeBody(r, v)
default:
return fmt.Errorf("Unrecognized message type: %v", c.mt)
}
}
// Write writes a message to the wire which contains the header followed by the body.
// The body is assumed to satisfy the msgp.Encodable interface.
func (c *msgpackCodec) Write(m *codec.Message, b interface{}) error {
switch m.Type {
case codec.Request:
h := Request{
ID: m.Id,
Method: m.Endpoint,
Body: b,
}
return msgp.Encode(c.rwc, &h)
case codec.Response:
h := Response{
ID: m.Id,
Body: b,
}
h.Error = m.Error
return msgp.Encode(c.rwc, &h)
case codec.Publication:
h := Notification{
Method: m.Endpoint,
Body: b,
}
return msgp.Encode(c.rwc, &h)
default:
return fmt.Errorf("Unrecognized message type: %v", m.Type)
}
}
func NewCodec(rwc io.ReadWriteCloser) codec.Codec {
return &msgpackCodec{
rwc: rwc,
}
}