[#290] client: Add WithURIAddress option

Add `WithURIAddress` option to client.
It parses passed address with
`url.ParseRequestURI` function and
use(or not) TLS over grpc connection
based on retrieved scheme('grpc' or
'grpcs').

Signed-off-by: Pavel Karpy <carpawell@nspcc.ru>
This commit is contained in:
Pavel Karpy 2021-05-27 15:21:58 +03:00 committed by Alex Vanin
parent 65080c8b69
commit 52c1c4c5ab
3 changed files with 284 additions and 9 deletions

View file

@ -2,11 +2,17 @@ package client
import (
"crypto/tls"
"net/url"
"time"
"google.golang.org/grpc"
)
const (
grpcScheme = "grpc"
grpcTLSScheme = "grpcs"
)
// Option is a Client's option.
type Option func(*cfg)
@ -40,6 +46,44 @@ func WithNetworkAddress(v string) Option {
}
}
// WithNetworkURIAddress combines WithNetworkAddress and WithTLSCfg options
// based on arguments.
//
// Do not use along with WithNetworkAddress and WithTLSCfg.
//
// Ignored if WithGRPCConn is provided.
func WithNetworkURIAddress(addr string, tlsCfg *tls.Config) []Option {
uri, err := url.ParseRequestURI(addr)
if err != nil {
return []Option{WithNetworkAddress(addr)}
}
// check if passed string was parsed correctly
// URIs that do not start with a slash after the scheme are interpreted as:
// `scheme:opaque` => if `opaque` is not empty, then it is supposed that URI
// is in `host:port` format
if uri.Opaque != "" {
return []Option{WithNetworkAddress(addr)}
}
switch uri.Scheme {
case grpcScheme:
tlsCfg = nil
case grpcTLSScheme:
if tlsCfg == nil {
tlsCfg = &tls.Config{}
}
default:
// not supported scheme
return nil
}
return []Option{
WithNetworkAddress(uri.Host),
WithTLSCfg(tlsCfg),
}
}
// WithDialTimeout returns option to specify
// dial timeout of the remote server connection.
//
@ -58,9 +102,7 @@ func WithDialTimeout(v time.Duration) Option {
// Ignored if WithGRPCConn is provided.
func WithTLSCfg(v *tls.Config) Option {
return func(c *cfg) {
if v != nil {
c.tlsCfg = v
}
c.tlsCfg = v
}
}