forked from wanzo-mini/mini-rpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
64 lines (53 loc) · 1.65 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
// Copyright 2022 <[email protected]>. All rights reserved.
// Use of this source code is governed by a git
// license that can be found in the LICENSE file.
package tinyrpc
import (
"io"
"net/rpc"
"github.com/zehuamama/tinyrpc/codec"
"github.com/zehuamama/tinyrpc/compressor"
"github.com/zehuamama/tinyrpc/serializer"
)
// Client rpc client based on net/rpc implementation
type Client struct {
*rpc.Client
}
//Option provides options for rpc
type Option func(o *options)
type options struct {
compressType compressor.CompressType
serializer serializer.Serializer
}
// WithCompress set client compression format
func WithCompress(c compressor.CompressType) Option {
return func(o *options) {
o.compressType = c
}
}
// WithSerializer set client serializer
func WithSerializer(serializer serializer.Serializer) Option {
return func(o *options) {
o.serializer = serializer
}
}
// NewClient Create a new rpc client
func NewClient(conn io.ReadWriteCloser, opts ...Option) *Client {
options := options{
compressType: compressor.Raw,
serializer: serializer.Proto,
}
for _, option := range opts {
option(&options)
}
return &Client{rpc.NewClientWithCodec(
codec.NewClientCodec(conn, options.compressType, options.serializer))}
}
// Call synchronously calls the rpc function
func (c *Client) Call(serviceMethod string, args interface{}, reply interface{}) error {
return c.Client.Call(serviceMethod, args, reply)
}
// AsyncCall asynchronously calls the rpc function and returns a channel of *rpc.Call
func (c *Client) AsyncCall(serviceMethod string, args interface{}, reply interface{}) chan *rpc.Call {
return c.Go(serviceMethod, args, reply, nil).Done
}