Skip to content

Commit f0f5dd4

Browse files
committed
Specify a custom dial function per config
1 parent 0004702 commit f0f5dd4

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

connector.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,16 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
8080
dialsLock.RLock()
8181
dial, ok := dials[mc.cfg.Net]
8282
dialsLock.RUnlock()
83-
if ok {
83+
84+
if c.cfg.DialFunc != nil {
85+
dctx := ctx
86+
if mc.cfg.Timeout > 0 {
87+
var cancel context.CancelFunc
88+
dctx, cancel = context.WithTimeout(ctx, c.cfg.Timeout)
89+
defer cancel()
90+
}
91+
mc.netConn, err = c.cfg.DialFunc(dctx, mc.cfg.Net, mc.cfg.Addr)
92+
} else if ok {
8493
dctx := ctx
8594
if mc.cfg.Timeout > 0 {
8695
var cancel context.CancelFunc

dsn.go

+10
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ package mysql
1010

1111
import (
1212
"bytes"
13+
"context"
1314
"crypto/rsa"
1415
"crypto/tls"
1516
"errors"
@@ -65,6 +66,15 @@ type Config struct {
6566
MultiStatements bool // Allow multiple statements in one query
6667
ParseTime bool // Parse time values to time.Time
6768
RejectReadOnly bool // Reject read-only connections
69+
70+
// DialFunc specifies the dial function for creating connections.
71+
// If DialFunc is nil, the connector will attempt to find a dial function from the global registry (registered with RegisterDialContext).
72+
// If no dial function is found even after checking the global registry, the net.Dialer will be used as a fallback.
73+
//
74+
// The dial function is responsible for establishing connections. By providing a custom dial function,
75+
// users can flexibly control the process of connection establishment. Custom dial functions can be registered in the global registry
76+
// to tailor connection behavior according to specific requirements.
77+
DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
6878
}
6979

7080
// NewConfig creates a new Config and sets default values.

0 commit comments

Comments
 (0)