add tls connect options
This commit is contained in:
parent
237e1539c1
commit
2b6be44627
33
mongodb.go
33
mongodb.go
|
@ -7,10 +7,41 @@ import (
|
||||||
"github.com/logrusorgru/aurora"
|
"github.com/logrusorgru/aurora"
|
||||||
"go.mongodb.org/mongo-driver/mongo"
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
"go.mongodb.org/mongo-driver/mongo/options"
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||||||
|
"go.mongodb.org/mongo-driver/mongo/readpref"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ConnectTLSOpts ...
|
||||||
|
type ConnectTLSOpts struct {
|
||||||
|
Host string
|
||||||
|
DBName string
|
||||||
|
ReplSet string
|
||||||
|
CaFilePath string
|
||||||
|
CertificateKeyFilePath string
|
||||||
|
CertificateKeyFilePassword string
|
||||||
|
}
|
||||||
|
|
||||||
var db *mongo.Database
|
var db *mongo.Database
|
||||||
|
|
||||||
|
// ConnectWithTLS ...
|
||||||
|
func ConnectWithTLS(opts ConnectTLSOpts) (*mongo.Database, error) {
|
||||||
|
ctx := context.Background()
|
||||||
|
uri := fmt.Sprintf("%s/?tls=true&tlsCAFile=%s&tlsCertificateKeyFile=%s&tlsCertificateKeyFilePassword=%s", opts.Host, opts.CaFilePath, opts.CertificateKeyFilePath, opts.CertificateKeyFilePassword)
|
||||||
|
readPref := readpref.SecondaryPreferred()
|
||||||
|
credential := options.Credential{
|
||||||
|
AuthMechanism: "MONGODB-X509",
|
||||||
|
}
|
||||||
|
clientOpts := options.Client().SetAuth(credential).SetReadPreference(readPref).SetReplicaSet(opts.ReplSet).ApplyURI(uri)
|
||||||
|
client, err := mongo.Connect(ctx, clientOpts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := client.Ping(ctx, readpref.SecondaryPreferred()); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
db = client.Database(opts.DBName)
|
||||||
|
return db, err
|
||||||
|
}
|
||||||
|
|
||||||
// Connect to mongo server
|
// Connect to mongo server
|
||||||
func Connect(host, user, password, dbName, mechanism, source string) (*mongo.Database, error) {
|
func Connect(host, user, password, dbName, mechanism, source string) (*mongo.Database, error) {
|
||||||
connectOptions := options.ClientOptions{}
|
connectOptions := options.ClientOptions{}
|
||||||
|
@ -31,7 +62,7 @@ func Connect(host, user, password, dbName, mechanism, source string) (*mongo.Dat
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println(aurora.Green("*** CONNECTED TO MONGODB: " + host))
|
fmt.Println(aurora.Green("*** CONNECTED TO MONGODB: " + host + " --- DB: " + dbName))
|
||||||
|
|
||||||
// Set data
|
// Set data
|
||||||
db = client.Database(dbName)
|
db = client.Database(dbName)
|
||||||
|
|
Loading…
Reference in New Issue