forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
86 lines (71 loc) · 1.87 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
package zrpc
import (
"log"
"time"
"github.com/tal-tech/go-zero/core/discov"
"github.com/tal-tech/go-zero/zrpc/internal"
"github.com/tal-tech/go-zero/zrpc/internal/auth"
"google.golang.org/grpc"
)
var (
WithDialOption = internal.WithDialOption
WithTimeout = internal.WithTimeout
WithUnaryClientInterceptor = internal.WithUnaryClientInterceptor
)
type (
ClientOption = internal.ClientOption
Client interface {
Conn() *grpc.ClientConn
}
RpcClient struct {
client Client
}
)
func MustNewClient(c RpcClientConf, options ...ClientOption) Client {
cli, err := NewClient(c, options...)
if err != nil {
log.Fatal(err)
}
return cli
}
func NewClient(c RpcClientConf, options ...ClientOption) (Client, error) {
var opts []ClientOption
if c.HasCredential() {
opts = append(opts, WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{
App: c.App,
Token: c.Token,
})))
}
if c.Timeout > 0 {
opts = append(opts, WithTimeout(time.Duration(c.Timeout)*time.Millisecond))
}
opts = append(opts, options...)
var client Client
var err error
if len(c.Endpoints) > 0 {
client, err = internal.NewClient(internal.BuildDirectTarget(c.Endpoints), opts...)
} else if err = c.Etcd.Validate(); err == nil {
client, err = internal.NewClient(internal.BuildDiscovTarget(c.Etcd.Hosts, c.Etcd.Key), opts...)
}
if err != nil {
return nil, err
}
return &RpcClient{
client: client,
}, nil
}
func NewClientNoAuth(c discov.EtcdConf, opts ...ClientOption) (Client, error) {
client, err := internal.NewClient(internal.BuildDiscovTarget(c.Hosts, c.Key), opts...)
if err != nil {
return nil, err
}
return &RpcClient{
client: client,
}, nil
}
func NewClientWithTarget(target string, opts ...ClientOption) (Client, error) {
return internal.NewClient(target, opts...)
}
func (rc *RpcClient) Conn() *grpc.ClientConn {
return rc.client.Conn()
}