Skip to content

Commit

Permalink
GRPC Client wrapper
Browse files Browse the repository at this point in the history
AB#8170
  • Loading branch information
eccles committed May 17, 2024
1 parent d6436b6 commit 8d08cb3
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 0 deletions.
75 changes: 75 additions & 0 deletions grpcclient/client.go
Original file line number Diff line number Diff line change
@@ -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
}
9 changes: 9 additions & 0 deletions grpcclient/grpc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package grpcclient

import (
"google.golang.org/grpc"
)

type UnaryClientInterceptor = grpc.UnaryClientInterceptor
type DialOption = grpc.DialOption
type ClientConn = grpc.ClientConn
7 changes: 7 additions & 0 deletions grpcclient/interface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package grpcclient

type ClientProvider interface {
Open() error
Close()
String() string
}
7 changes: 7 additions & 0 deletions grpcclient/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package grpcclient

import (
"github.com/datatrails/go-datatrails-common/logger"
)

type Logger = logger.Logger

0 comments on commit 8d08cb3

Please sign in to comment.