diff --git a/grpcclient/client.go b/grpcclient/client.go new file mode 100644 index 0000000..a172b50 --- /dev/null +++ b/grpcclient/client.go @@ -0,0 +1,75 @@ +package grpcclient + +import ( + "google.golang.org/grpc" +) + +type Client struct { + name string + log Logger + address string + conn *grpc.ClientConn + interceptors []grpc.UnaryClientInterceptor +} + +func (g *Client) Open() error { + if g.conn != nil { + return nil + } + + var err error + var conn *grpc.ClientConn + + g.log.Debugf("Open %s client at %v", g.name, g.address) + opts := []grpc.DialOption{} + for _, interceptor := range g.interceptors { + opts = append( + opts, + grpc.WithUnaryInterceptor(interceptor), + ) + } + conn, err = grpc.Dial(g.address, opts...) + if err != nil { + return err + } + g.conn = conn + g.log.Debugf("Open %s client successful", g.name) + return nil +} + +func (g *Client) Close() { + if g.conn != nil { + g.log.Debugf("Close %s client at %v", g.name, g.address) + g.conn.Close() + g.conn = nil + } +} + +func (g *Client) String() string { + return g.name +} + +func (g *Client) Connector() *ClientConn { + return g.conn +} + +type ClientOption func(*Client) + +func WithUnaryInterceptor(u UnaryClientInterceptor) ClientOption { + return func(t *Client) { + t.interceptors = append(t.interceptors, u) + } +} + +func New(log Logger, name string, address string, opts ...ClientOption) *Client { + t := Client{ + name: name, + address: address, + log: log.WithIndex("grpcclient", name), + interceptors: []grpc.UnaryClientInterceptor{}, + } + for _, opt := range opts { + opt(&t) + } + return &t +} diff --git a/grpcclient/grpc.go b/grpcclient/grpc.go new file mode 100644 index 0000000..9c59e00 --- /dev/null +++ b/grpcclient/grpc.go @@ -0,0 +1,9 @@ +package grpcclient + +import ( + "google.golang.org/grpc" +) + +type UnaryClientInterceptor = grpc.UnaryClientInterceptor +type DialOption = grpc.DialOption +type ClientConn = grpc.ClientConn diff --git a/grpcclient/interface.go b/grpcclient/interface.go new file mode 100644 index 0000000..75fe177 --- /dev/null +++ b/grpcclient/interface.go @@ -0,0 +1,7 @@ +package grpcclient + +type ClientProvider interface { + Open() error + Close() + String() string +} diff --git a/grpcclient/logger.go b/grpcclient/logger.go new file mode 100644 index 0000000..37439f0 --- /dev/null +++ b/grpcclient/logger.go @@ -0,0 +1,7 @@ +package grpcclient + +import ( + "github.com/datatrails/go-datatrails-common/logger" +) + +type Logger = logger.Logger