Skip to content

Commit 4c45491

Browse files
committed
dsn: move DSN normalization to separate func
1 parent 8667b6c commit 4c45491

File tree

1 file changed

+31
-24
lines changed

1 file changed

+31
-24
lines changed

dsn.go

+31-24
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,35 @@ func NewConfig() *Config {
6464
AllowNativePasswords: true,
6565
}
6666
}
67+
68+
func (cfg *Config) normalize() error {
69+
if cfg.InterpolateParams && unsafeCollations[cfg.Collation] {
70+
return errInvalidDSNUnsafeCollation
71+
}
72+
73+
// Set default network if empty
74+
if cfg.Net == "" {
75+
cfg.Net = "tcp"
76+
}
77+
78+
// Set default address if empty
79+
if cfg.Addr == "" {
80+
switch cfg.Net {
81+
case "tcp":
82+
cfg.Addr = "127.0.0.1:3306"
83+
case "unix":
84+
cfg.Addr = "/tmp/mysql.sock"
85+
default:
86+
errors.New("default addr for network '" + cfg.Net + "' unknown")
87+
}
88+
89+
} else if cfg.Net == "tcp" {
90+
cfg.Addr = ensureHavePort(cfg.Addr)
91+
}
92+
93+
return nil
94+
}
95+
6796
// FormatDSN formats the given Config into a DSN string which can be passed to
6897
// the driver.
6998
func (cfg *Config) FormatDSN() string {
@@ -348,31 +377,9 @@ func ParseDSN(dsn string) (cfg *Config, err error) {
348377
return nil, errInvalidDSNNoSlash
349378
}
350379

351-
if cfg.InterpolateParams && unsafeCollations[cfg.Collation] {
352-
return nil, errInvalidDSNUnsafeCollation
353-
}
354-
355-
// Set default network if empty
356-
if cfg.Net == "" {
357-
cfg.Net = "tcp"
358-
}
359-
360-
// Set default address if empty
361-
if cfg.Addr == "" {
362-
switch cfg.Net {
363-
case "tcp":
364-
cfg.Addr = "127.0.0.1:3306"
365-
case "unix":
366-
cfg.Addr = "/tmp/mysql.sock"
367-
default:
368-
return nil, errors.New("default addr for network '" + cfg.Net + "' unknown")
369-
}
370-
380+
if err = cfg.normalize(); err != nil {
381+
return nil, err
371382
}
372-
if cfg.Net == "tcp" {
373-
cfg.Addr = ensureHavePort(cfg.Addr)
374-
}
375-
376383
return
377384
}
378385

0 commit comments

Comments
 (0)