From 9253dac7533bd19be35e94e68c53b5192565737b Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Thu, 20 Aug 2020 12:28:00 +0300 Subject: [PATCH] v2: Add cross-service client package Add package with cross-service client utilities for working with transport protocols and basic network types. Signed-off-by: Leonard Lyubich --- v2/client/options.go | 108 +++++++++++++++++++++++++++++++++++++++++++ v2/client/proto.go | 23 +++++++++ 2 files changed, 131 insertions(+) create mode 100644 v2/client/options.go create mode 100644 v2/client/proto.go diff --git a/v2/client/options.go b/v2/client/options.go new file mode 100644 index 0000000..3dcdff1 --- /dev/null +++ b/v2/client/options.go @@ -0,0 +1,108 @@ +package client + +import ( + "context" + "net" + + "google.golang.org/grpc" +) + +type Option func(*cfg) + +type cfg struct { + addr string + + conn net.Conn + + gRPC cfgGRPC +} + +type cfgGRPC struct { + dialCtx context.Context + + dialOpts []grpc.DialOption + + conn *grpc.ClientConn +} + +func defaultCfg() *cfg { + return &cfg{ + gRPC: cfgGRPC{ + dialCtx: context.Background(), + dialOpts: []grpc.DialOption{ + grpc.WithInsecure(), + }, + }, + } +} + +func NewGRPCClientConn(opts ...Option) (*grpc.ClientConn, error) { + cfg := defaultCfg() + + for i := range opts { + opts[i](cfg) + } + + var err error + + if cfg.gRPC.conn == nil { + if cfg.conn != nil { + if cfg.addr == "" { + cfg.addr = cfg.conn.RemoteAddr().String() + } + + cfg.gRPC.dialOpts = append(cfg.gRPC.dialOpts, + grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { + return cfg.conn, nil + }), + ) + } + + cfg.gRPC.conn, err = grpc.DialContext(cfg.gRPC.dialCtx, cfg.addr, cfg.gRPC.dialOpts...) + if err != nil { + return nil, err + } + } + + return cfg.gRPC.conn, err +} + +func WithNetworkAddress(v string) Option { + return func(c *cfg) { + if v != "" { + c.addr = v + } + } +} + +func WithNetConn(v net.Conn) Option { + return func(c *cfg) { + if v != nil { + c.conn = v + } + } +} + +func WithGRPCDialContext(v context.Context) Option { + return func(c *cfg) { + if v != nil { + c.gRPC.dialCtx = v + } + } +} + +func WithGRPCDialOpts(v []grpc.DialOption) Option { + return func(c *cfg) { + if len(v) > 0 { + c.gRPC.dialOpts = v + } + } +} + +func WithGRPCConn(v *grpc.ClientConn) Option { + return func(c *cfg) { + if v != nil { + c.gRPC.conn = v + } + } +} diff --git a/v2/client/proto.go b/v2/client/proto.go new file mode 100644 index 0000000..f6a6aa6 --- /dev/null +++ b/v2/client/proto.go @@ -0,0 +1,23 @@ +package client + +import ( + "github.com/pkg/errors" +) + +type Protocol uint32 + +const ( + _ Protocol = iota + ProtoGRPC +) + +var ErrProtoUnsupported = errors.New("unsupported protocol") + +func (p Protocol) String() string { + switch p { + case ProtoGRPC: + return "GRPC" + default: + return "UNKNOWN" + } +}