2020-08-20 09:28:00 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
2020-11-23 11:04:33 +00:00
|
|
|
"time"
|
2020-08-20 09:28:00 +00:00
|
|
|
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Option func(*cfg)
|
|
|
|
|
|
|
|
type cfg struct {
|
|
|
|
addr string
|
|
|
|
|
|
|
|
conn net.Conn
|
|
|
|
|
|
|
|
gRPC cfgGRPC
|
2020-11-23 11:04:33 +00:00
|
|
|
|
|
|
|
dialTimeout time.Duration
|
2020-08-20 09:28:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type cfgGRPC struct {
|
|
|
|
dialOpts []grpc.DialOption
|
|
|
|
|
|
|
|
conn *grpc.ClientConn
|
|
|
|
}
|
|
|
|
|
2020-11-23 11:04:33 +00:00
|
|
|
const defaultDialTimeout = 5 * time.Second
|
|
|
|
|
2020-08-20 09:28:00 +00:00
|
|
|
func defaultCfg() *cfg {
|
|
|
|
return &cfg{
|
|
|
|
gRPC: cfgGRPC{
|
|
|
|
dialOpts: []grpc.DialOption{
|
|
|
|
grpc.WithInsecure(),
|
|
|
|
},
|
|
|
|
},
|
2020-11-23 11:04:33 +00:00
|
|
|
dialTimeout: defaultDialTimeout,
|
2020-08-20 09:28:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-11-23 11:04:33 +00:00
|
|
|
dialCtx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout)
|
|
|
|
|
|
|
|
cfg.gRPC.conn, err = grpc.DialContext(dialCtx, cfg.addr, cfg.gRPC.dialOpts...)
|
|
|
|
|
|
|
|
cancel()
|
2020-08-20 09:28:00 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-23 11:04:33 +00:00
|
|
|
func WithDialTimeout(v time.Duration) Option {
|
2020-08-20 09:28:00 +00:00
|
|
|
return func(c *cfg) {
|
2020-11-23 11:04:33 +00:00
|
|
|
if v > 0 {
|
|
|
|
c.dialTimeout = v
|
2020-08-20 09:28:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|