forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 3
/
codec.go
109 lines (92 loc) · 1.98 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
package bsonrpc
import (
"io"
"github.com/micro/go-bson"
"github.com/micro/go-micro/codec"
)
const (
bufferSize = 4096
)
type clientCodec struct {
rwc io.ReadWriteCloser
}
type serverCodec struct {
rwc io.ReadWriteCloser
}
type request struct {
ServiceMethod string
Seq uint64
}
type response struct {
ServiceMethod string
Seq uint64
Error string
}
func (c *clientCodec) Write(m *codec.Message, body interface{}) error {
if err := bson.MarshalToStream(c.rwc, &request{
ServiceMethod: m.Method,
Seq: m.Id,
}); err != nil {
return err
}
if err := bson.MarshalToStream(c.rwc, body); err != nil {
return err
}
return nil
}
func (c *clientCodec) ReadHeader(m *codec.Message) error {
r := &response{}
if err := bson.UnmarshalFromStream(c.rwc, r); err != nil {
return err
}
m.Id = r.Seq
m.Method = r.ServiceMethod
m.Error = r.Error
return nil
}
func (c *clientCodec) ReadBody(body interface{}) error {
if body == nil {
return nil
}
return bson.UnmarshalFromStream(c.rwc, body)
}
func (c *clientCodec) Close() error {
return c.rwc.Close()
}
func (s *serverCodec) ReadHeader(m *codec.Message) error {
r := &request{}
if err := bson.UnmarshalFromStream(s.rwc, r); err != nil {
return err
}
m.Id = r.Seq
m.Method = r.ServiceMethod
return nil
}
func (s *serverCodec) ReadBody(body interface{}) error {
if body == nil {
return nil
}
return bson.UnmarshalFromStream(s.rwc, body)
}
func (s *serverCodec) Write(m *codec.Message, body interface{}) error {
if err := bson.MarshalToStream(s.rwc, &response{
ServiceMethod: m.Method,
Seq: m.Id,
Error: m.Error,
}); err != nil {
return err
}
if err := bson.MarshalToStream(s.rwc, body); err != nil {
return err
}
return nil
}
func (s *serverCodec) Close() error {
return s.rwc.Close()
}
func newClientCodec(rwc io.ReadWriteCloser) *clientCodec {
return &clientCodec{rwc}
}
func newServerCodec(rwc io.ReadWriteCloser) *serverCodec {
return &serverCodec{rwc}
}