Skip to content

Commit 52276c3

Browse files
committed
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.
1 parent f1dd3d5 commit 52276c3

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

options.go

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -129,16 +129,7 @@ func (opt *Options) init() {
129129
opt.DialTimeout = 5 * time.Second
130130
}
131131
if opt.Dialer == nil {
132-
opt.Dialer = func(ctx context.Context, network, addr string) (net.Conn, error) {
133-
netDialer := &net.Dialer{
134-
Timeout: opt.DialTimeout,
135-
KeepAlive: 5 * time.Minute,
136-
}
137-
if opt.TLSConfig == nil {
138-
return netDialer.DialContext(ctx, network, addr)
139-
}
140-
return tls.DialWithDialer(netDialer, network, addr, opt.TLSConfig)
141-
}
132+
opt.Dialer = DefaultDialer(opt)
142133
}
143134
if opt.PoolSize == 0 {
144135
opt.PoolSize = 10 * runtime.GOMAXPROCS(0)
@@ -189,6 +180,21 @@ func (opt *Options) clone() *Options {
189180
return &clone
190181
}
191182

183+
// DefaultDialer returns a function that will be used as the default dialer
184+
// when none is specified in Options.Dialer.
185+
func DefaultDialer(opt *Options) func(context.Context, string, string) (net.Conn, error) {
186+
return func(ctx context.Context, network, addr string) (net.Conn, error) {
187+
netDialer := &net.Dialer{
188+
Timeout: opt.DialTimeout,
189+
KeepAlive: 5 * time.Minute,
190+
}
191+
if opt.TLSConfig == nil {
192+
return netDialer.DialContext(ctx, network, addr)
193+
}
194+
return tls.DialWithDialer(netDialer, network, addr, opt.TLSConfig)
195+
}
196+
}
197+
192198
// ParseURL parses an URL into Options that can be used to connect to Redis.
193199
// Scheme is required.
194200
// There are two connection types: by tcp socket and by unix socket.

0 commit comments

Comments
 (0)