2016-05-13 20:42:09 +00:00
|
|
|
package mongodb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
|
|
|
"errors"
|
|
|
|
"net"
|
|
|
|
"net/url"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"gopkg.in/mgo.v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Unfortunately, mgo doesn't support the ssl parameter in its MongoDB URI parsing logic, so we have to handle that
|
|
|
|
// ourselves. See https://github.com/go-mgo/mgo/issues/84
|
2016-07-01 13:12:26 +00:00
|
|
|
func parseMongoURI(rawUri string) (*mgo.DialInfo, error) {
|
|
|
|
uri, err := url.Parse(rawUri)
|
2016-05-13 20:42:09 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-07-01 13:12:26 +00:00
|
|
|
|
|
|
|
info := mgo.DialInfo{
|
|
|
|
Addrs: strings.Split(uri.Host, ","),
|
|
|
|
Database: strings.TrimPrefix(uri.Path, "/"),
|
|
|
|
Timeout: 10 * time.Second,
|
|
|
|
}
|
|
|
|
|
|
|
|
if uri.User != nil {
|
|
|
|
info.Username = uri.User.Username()
|
|
|
|
password, _ := uri.User.Password()
|
|
|
|
info.Password = password
|
|
|
|
}
|
|
|
|
|
|
|
|
query := uri.Query()
|
|
|
|
for key, values := range query {
|
|
|
|
var value string
|
|
|
|
if len(values) > 0 {
|
|
|
|
value = values[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
switch key {
|
2016-05-13 20:42:09 +00:00
|
|
|
case "authSource":
|
2016-07-01 13:12:26 +00:00
|
|
|
info.Source = value
|
2016-05-13 20:42:09 +00:00
|
|
|
case "authMechanism":
|
2016-07-01 13:12:26 +00:00
|
|
|
info.Mechanism = value
|
2016-05-13 20:42:09 +00:00
|
|
|
case "gssapiServiceName":
|
2016-07-01 13:12:26 +00:00
|
|
|
info.Service = value
|
2016-05-13 20:42:09 +00:00
|
|
|
case "replicaSet":
|
2016-07-01 13:12:26 +00:00
|
|
|
info.ReplicaSetName = value
|
2016-05-13 20:42:09 +00:00
|
|
|
case "maxPoolSize":
|
2016-07-01 13:12:26 +00:00
|
|
|
poolLimit, err := strconv.Atoi(value)
|
2016-05-13 20:42:09 +00:00
|
|
|
if err != nil {
|
2016-07-01 13:12:26 +00:00
|
|
|
return nil, errors.New("bad value for maxPoolSize: " + value)
|
2016-05-13 20:42:09 +00:00
|
|
|
}
|
2016-07-01 13:12:26 +00:00
|
|
|
info.PoolLimit = poolLimit
|
2016-05-13 20:42:09 +00:00
|
|
|
case "ssl":
|
2016-07-01 13:12:26 +00:00
|
|
|
if value == "true" {
|
|
|
|
info.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
|
|
|
|
return tls.Dial("tcp", addr.String(), &tls.Config{})
|
|
|
|
}
|
2016-05-13 20:42:09 +00:00
|
|
|
}
|
|
|
|
case "connect":
|
2016-07-01 13:12:26 +00:00
|
|
|
if value == "direct" {
|
|
|
|
info.Direct = true
|
2016-05-13 20:42:09 +00:00
|
|
|
break
|
|
|
|
}
|
2016-07-01 13:12:26 +00:00
|
|
|
if value == "replicaSet" {
|
2016-05-13 20:42:09 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
fallthrough
|
|
|
|
default:
|
2016-07-01 13:12:26 +00:00
|
|
|
return nil, errors.New("unsupported connection URL option: " + key + "=" + value)
|
2016-05-13 20:42:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-01 13:12:26 +00:00
|
|
|
return &info, nil
|
2016-05-13 20:42:09 +00:00
|
|
|
}
|