forked from wanzo-mini/mini-rpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
60 lines (48 loc) · 1.52 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
// Copyright 2022 <mzh.scnu@qq.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// 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"
)
// Client tinyrpc client based on net/rpc implementation
type Client struct {
*rpc.Client
}
//Option provides options for tinyrpc client
type Option interface {
apply(*options)
}
type options struct {
compressType compressor.CompressType
}
type compressOption compressor.CompressType
func (c compressOption) apply(opt *options) {
opt.compressType = compressor.CompressType(c)
}
// WithCompress set client compression format
func WithCompress(c compressor.CompressType) Option {
return compressOption(c)
}
// NewClient Create a new tinyrpc client
func NewClient(conn io.ReadWriteCloser, opts ...Option) *Client {
options := options{
compressType: compressor.Raw,
}
for _, o := range opts {
o.apply(&options)
}
return &Client{rpc.NewClientWithCodec(
codec.NewClientCodec(conn, options.compressType))}
}
// Call synchronously calls the tinyrpc function
func (c *Client) Call(serviceMethod string, args interface{}, reply interface{}) error {
return c.Client.Call(serviceMethod, args, reply)
}
// AsyncCall asynchronously calls the tinyrpc 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
}