Skip to content

Commit 7785c74

Browse files
bgaifullinarnehormann
authored andcommitted
use default port if port is missing in dsn (go-sql-driver#668) (go-sql-driver#669)
1 parent be22b30 commit 7785c74

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,8 @@ See [net.Dial](https://golang.org/pkg/net/#Dial) for more information which netw
101101
In general you should use an Unix domain socket if available and TCP otherwise for best performance.
102102

103103
#### Address
104-
For TCP and UDP networks, addresses have the form `host:port`.
104+
For TCP and UDP networks, addresses have the form `host[:port]`.
105+
If `port` is omitted, the default port will be used.
105106
If `host` is a literal IPv6 address, it must be enclosed in square brackets.
106107
The functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form.
107108

dsn.go

+10
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,9 @@ func ParseDSN(dsn string) (cfg *Config, err error) {
376376
}
377377

378378
}
379+
if cfg.Net == "tcp" {
380+
cfg.Addr = ensureHavePort(cfg.Addr)
381+
}
379382

380383
return
381384
}
@@ -575,3 +578,10 @@ func parseDSNParams(cfg *Config, params string) (err error) {
575578

576579
return
577580
}
581+
582+
func ensureHavePort(addr string) string {
583+
if _, _, err := net.SplitHostPort(addr); err != nil {
584+
return net.JoinHostPort(addr, "3306")
585+
}
586+
return addr
587+
}

dsn_test.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,14 @@ var testDSNs = []struct {
6565
}, {
6666
"unix/?arg=%2Fsome%2Fpath.ext",
6767
&Config{Net: "unix", Addr: "/tmp/mysql.sock", Params: map[string]string{"arg": "/some/path.ext"}, Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true},
68-
}}
68+
}, {
69+
"tcp(127.0.0.1)/dbname",
70+
&Config{Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true},
71+
}, {
72+
"tcp(de:ad:be:ef::ca:fe)/dbname",
73+
&Config{Net: "tcp", Addr: "[de:ad:be:ef::ca:fe]:3306", DBName: "dbname", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true},
74+
},
75+
}
6976

7077
func TestDSNParser(t *testing.T) {
7178
for i, tst := range testDSNs {

0 commit comments

Comments
 (0)