net/url: allow commas in hostnames for mongodb urls

A valid MongoDB URL can contain commas
to include multiple host:port pairs.
The current parseHost function splits the port
starting from the first colon (:),
but for MongoDB URLs that contain multiple host:port pairs,
it needs to split from the last colon (:).

Fixes #78077

Change-Id: I9a11f9295d0bc940626d3c6e9db2704237019b51
GitHub-Last-Rev: 5ca2276324
GitHub-Pull-Request: golang/go#77933
Reviewed-on: https://go-review.googlesource.com/c/go/+/751360
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Sean Liao <sean@liao.dev>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Sean Liao <sean@liao.dev>
Reviewed-by: Damien Neil <dneil@google.com>
This commit is contained in:
yueyoum
2026-03-13 03:04:12 +00:00
committed by Gopher Robot
parent a61fd42897
commit a481ef071e
2 changed files with 28 additions and 0 deletions

View File

@@ -617,6 +617,13 @@ func parseHost(scheme, host string) (string, error) {
// continue to permit it for postgres:// URLs only.
// https://go.dev/issue/75223
i = lastColon
} else if scheme == "mongodb" || scheme == "mongodb+srv" {
// In a MongoDB connection URI, commas are used to separate
// multiple host addresses when connecting to a replica set or a sharded cluster.
// https://www.mongodb.com/docs/manual/reference/connection-string-formats/
// Example:
// mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017
i = lastColon
} else if urlstrictcolons.Value() == "0" {
urlstrictcolons.IncNonDefault()
i = lastColon

View File

@@ -629,6 +629,27 @@ var urltests = []URLTest{
},
"postgresql://host1:1,host2:2,host3:3",
},
// Mongodb URLs can include a comma-separated list of host:post hosts.
{
"mongodb://user:password@host1:1,host2:2,host3:3",
&URL{
Scheme: "mongodb",
User: UserPassword("user", "password"),
Host: "host1:1,host2:2,host3:3",
Path: "",
},
"",
},
{
"mongodb+srv://user:password@host1:1,host2:2,host3:3",
&URL{
Scheme: "mongodb+srv",
User: UserPassword("user", "password"),
Host: "host1:1,host2:2,host3:3",
Path: "",
},
"",
},
}
// more useful string for debugging than fmt's struct printer