forked from Terry-Mao/protorpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_codec.go
57 lines (50 loc) · 1.09 KB
/
client_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
package protorpc
import (
"bufio"
"bytes"
"encoding/binary"
"github.com/gogo/protobuf/proto"
"io"
)
type pbClientCodec struct {
rwc io.ReadWriteCloser
reqBuf bytes.Buffer
argsBuf bytes.Buffer
wr *bufio.Writer
rr *bufio.Reader
packBuf [binary.MaxVarintLen32]byte
}
// NewPbClientCodec returns a new ClientCodec using Protobuf-RPC on conn.
func NewPbClientCodec(rwc io.ReadWriteCloser, rr *bufio.Reader, wr *bufio.Writer) ClientCodec {
p := new(pbClientCodec)
p.rwc = rwc
p.wr = wr
p.rr = rr
return p
}
func (c *pbClientCodec) WriteRequest(r *Request, p proto.Message) (err error) {
var (
rb, pb []byte
)
rb, err = marshal(&c.reqBuf, r)
if err != nil {
return
}
pb, err = marshal(&c.argsBuf, p)
if err != nil {
return
}
if err = sendFrame(c.wr, c.packBuf[:], rb, pb); err != nil {
return
}
return c.wr.Flush()
}
func (c *pbClientCodec) ReadResponseHeader(r *Response) error {
return recvFrame(c.rr, r)
}
func (c *pbClientCodec) ReadResponseBody(b proto.Message) error {
return recvFrame(c.rr, b)
}
func (c *pbClientCodec) Close() error {
return c.rwc.Close()
}