From a481ef071e0b30b33b2857919957be151b2d2a6d Mon Sep 17 00:00:00 2001 From: yueyoum Date: Fri, 13 Mar 2026 03:04:12 +0000 Subject: [PATCH] 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: 5ca22763248214b2ea3f22d56c82fc01df9f8dba GitHub-Pull-Request: golang/go#77933 Reviewed-on: https://go-review.googlesource.com/c/go/+/751360 Reviewed-by: Carlos Amedee Reviewed-by: Sean Liao LUCI-TryBot-Result: Go LUCI Auto-Submit: Sean Liao Reviewed-by: Damien Neil --- src/net/url/url.go | 7 +++++++ src/net/url/url_test.go | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/net/url/url.go b/src/net/url/url.go index 3c49f0527d..092588de0c 100644 --- a/src/net/url/url.go +++ b/src/net/url/url.go @@ -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 diff --git a/src/net/url/url_test.go b/src/net/url/url_test.go index b048989b6c..790b025fda 100644 --- a/src/net/url/url_test.go +++ b/src/net/url/url_test.go @@ -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