From 52276c393d8983d8475438f152d4744fb0569d94 Mon Sep 17 00:00:00 2001 From: nick comer Date: Fri, 14 Jan 2022 16:01:09 -0500 Subject: [PATCH] feat: extract dialer to `DefaultDialer` to allow wrapping Allowing the default dialing function to be wrapped allows for library users to let the library continue to own the logic for dialing and let users wrap the function for more observability. My use case is to override `Options.Dialer` and add Jaeger tracing to gain insight into the cost of new connections on a latency sensitive API. ```go defDialer := redis.DefaultDialer(opts) opts.Dialer = func(ctx context.Context, network, addr string) (net.Conn, error) { span, ctx := opentracing.StartSpanFromContext(ctx, "cache-repo-redis: new redis connection") defer span.Finish() return defDialer(ctx, network, addr) } ``` Without this, I end up needing to copy-paste the code from the internal code, which is less-than-ideal since I don't want to own the maintenance of this logic. --- options.go | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/options.go b/options.go index a4abe32c..cbdb54ec 100644 --- a/options.go +++ b/options.go @@ -129,16 +129,7 @@ func (opt *Options) init() { opt.DialTimeout = 5 * time.Second } if opt.Dialer == nil { - opt.Dialer = func(ctx context.Context, network, addr string) (net.Conn, error) { - netDialer := &net.Dialer{ - Timeout: opt.DialTimeout, - KeepAlive: 5 * time.Minute, - } - if opt.TLSConfig == nil { - return netDialer.DialContext(ctx, network, addr) - } - return tls.DialWithDialer(netDialer, network, addr, opt.TLSConfig) - } + opt.Dialer = DefaultDialer(opt) } if opt.PoolSize == 0 { opt.PoolSize = 10 * runtime.GOMAXPROCS(0) @@ -189,6 +180,21 @@ func (opt *Options) clone() *Options { return &clone } +// DefaultDialer returns a function that will be used as the default dialer +// when none is specified in Options.Dialer. +func DefaultDialer(opt *Options) func(context.Context, string, string) (net.Conn, error) { + return func(ctx context.Context, network, addr string) (net.Conn, error) { + netDialer := &net.Dialer{ + Timeout: opt.DialTimeout, + KeepAlive: 5 * time.Minute, + } + if opt.TLSConfig == nil { + return netDialer.DialContext(ctx, network, addr) + } + return tls.DialWithDialer(netDialer, network, addr, opt.TLSConfig) + } +} + // ParseURL parses an URL into Options that can be used to connect to Redis. // Scheme is required. // There are two connection types: by tcp socket and by unix socket.