forked from vitessio/vitess
/
client.go
104 lines (91 loc) · 2.46 KB
/
client.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
// Package pbrpc implements a ClientCodec and ServerCodec
// for the rpcplus package using Protocol Buffers.
package pbrpc
import (
"io"
"net"
"sync"
"github.com/golang/protobuf/proto"
rpc "github.com/youtube/vitess/go/rpcplus"
)
// NewClientCodec returns a new rpc.ClientCodec using Protobuf on conn.
func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec {
return &pbClientCodec{rwc: conn}
}
// NewClient returns a new rpc.Client to handle requests to the
// set of services at the other end of the connection.
func NewClient(conn io.ReadWriteCloser) *rpc.Client {
return rpc.NewClientWithCodec(NewClientCodec(conn))
}
// Dial connects to a Protobuf-RPC server at the specified network address.
func Dial(network, address string) (*rpc.Client, error) {
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
return NewClient(conn), err
}
type pbClientCodec struct {
mu sync.Mutex
rwc io.ReadWriteCloser
}
// WriteRequest - implement rpc.ClientCodec interface.
func (c *pbClientCodec) WriteRequest(r *rpc.Request, body interface{}) (err error) {
// Use a mutex to guarantee the header/body are written in the correct order.
c.mu.Lock()
defer c.mu.Unlock()
// This is protobuf, of course we copy it.
pbr := &Request{ServiceMethod: &r.ServiceMethod, Seq: &r.Seq}
data, err := proto.Marshal(pbr)
if err != nil {
return
}
_, err = WriteNetString(c.rwc, data)
if err != nil {
return
}
// Of course this is a protobuf! Trust me or detonate the program.
data, err = proto.Marshal(body.(proto.Message))
if err != nil {
return
}
_, err = WriteNetString(c.rwc, data)
if err != nil {
return
}
if flusher, ok := c.rwc.(flusher); ok {
err = flusher.Flush()
}
return
}
// ReadResponseHeader - implement rpc.ClientCodec interface.
func (c *pbClientCodec) ReadResponseHeader(r *rpc.Response) error {
data, err := ReadNetString(c.rwc)
if err != nil {
return err
}
rtmp := new(Response)
err = proto.Unmarshal(data, rtmp)
if err != nil {
return err
}
r.ServiceMethod = *rtmp.ServiceMethod
r.Seq = *rtmp.Seq
r.Error = *rtmp.Error
return nil
}
// ReadResponseBody - implement rpc.ClientCodec interface.
func (c *pbClientCodec) ReadResponseBody(body interface{}) error {
data, err := ReadNetString(c.rwc)
if err != nil {
return err
}
if body != nil {
return proto.Unmarshal(data, body.(proto.Message))
}
return nil
}
// Close - implement rpc.ClientCodec interface.
func (c *pbClientCodec) Close() error {
return c.rwc.Close()
}