forked from hidevopsio/hiboot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
59 lines (53 loc) · 1.64 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
package grpc
import (
"github.com/hidevopsio/hiboot/pkg/factory"
"github.com/hidevopsio/hiboot/pkg/log"
"github.com/hidevopsio/hiboot/pkg/utils/reflector"
"google.golang.org/grpc"
)
// ClientConnector interface is response for creating grpc client connection
type ClientConnector interface {
Connect(name string, cb interface{}, prop *ClientProperties) (err error)
}
type clientConnector struct {
instantiateFactory factory.InstantiateFactory
}
func newClientConnector(instantiateFactory factory.InstantiateFactory) ClientConnector {
return &clientConnector{
instantiateFactory: instantiateFactory,
}
}
// Connect connect to grpc server from client
func (c *clientConnector) Connect(name string, cb interface{}, prop *ClientProperties) (err error) {
host := prop.Host
if host == "" {
host = name
}
address := host + ":" + prop.Port
conn := c.instantiateFactory.GetInstance(name)
if conn == nil {
// connect to grpc server
conn, err = grpc.Dial(address, grpc.WithInsecure())
c.instantiateFactory.SetInstance(name, conn)
if err != nil {
log.Errorf("failed to connect to grpc server %v", address)
return
}
log.Infof("gRPC client connected to: %v", address)
}
if cb != nil {
// get return type for register instance name
gRpcCli, err := reflector.CallFunc(cb, conn)
if err == nil {
clientInstanceName, err := reflector.GetName(gRpcCli)
if err == nil {
// register grpc client
c.instantiateFactory.SetInstance(clientInstanceName, gRpcCli)
// register clientConn
c.instantiateFactory.SetInstance(clientInstanceName+"Conn", conn)
log.Infof("Registered gRPC client %v", clientInstanceName)
}
}
}
return nil
}