Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mongodb: Connection URL parser improved #705

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions adapter/mongo/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,9 @@ import (
"strings"
)

const connectionScheme = `mongodb`

// ConnectionURL implements a MongoDB connection struct.
type ConnectionURL struct {
Scheme string
User string
Password string
Host string
Expand All @@ -39,11 +38,6 @@ type ConnectionURL struct {
}

func (c ConnectionURL) String() (s string) {

if c.Database == "" {
return ""
}

vv := url.Values{}

// Do we have any options?
Expand All @@ -69,7 +63,7 @@ func (c ConnectionURL) String() (s string) {

// Building URL.
u := url.URL{
Scheme: connectionScheme,
Scheme: c.Scheme,
Path: c.Database,
Host: c.Host,
User: userInfo,
Expand All @@ -80,17 +74,20 @@ func (c ConnectionURL) String() (s string) {
}

// ParseURL parses s into a ConnectionURL struct.
// See https://www.mongodb.com/docs/manual/reference/connection-string/
func ParseURL(s string) (conn ConnectionURL, err error) {
var u *url.URL

if !strings.HasPrefix(s, connectionScheme+"://") {
return conn, fmt.Errorf(`Expecting mongodb:// connection scheme.`)
hasPrefix := strings.HasPrefix(s, "mongodb://") || strings.HasPrefix(s, "mongodb+srv://")
if !hasPrefix {
return conn, fmt.Errorf("invalid scheme")
}

if u, err = url.Parse(s); err != nil {
return conn, err
}

conn.Scheme = u.Scheme
conn.Host = u.Host

// Deleting / from start of the string.
Expand Down
18 changes: 18 additions & 0 deletions adapter/mongo/connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ func TestParseConnectionURL(t *testing.T) {
t.Fatal(err)
}

if u.Scheme != "mongodb" {
t.Fatal("Invalid scheme")
}

if u.Database != "another_database" {
t.Fatal("Failed to get database.")
}
Expand Down Expand Up @@ -132,4 +136,18 @@ func TestParseConnectionURL(t *testing.T) {
t.Fatal("Expecting error.")
}

s = "mongodb+srv://myDatabaseUser:D1fficultP%[email protected]:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000"

if u, err = ParseURL(s); err != nil {
t.Fatal(err)
}

if u.Scheme != "mongodb+srv" {
t.Fatal("Invalid scheme")
}

if u.Database != "" {
t.Fatal("Invalid database")
}

}