2021-08-09 03:20:27 +00:00
|
|
|
package mongodb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/logrusorgru/aurora"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
2022-02-22 08:24:31 +00:00
|
|
|
"go.mongodb.org/mongo-driver/mongo/readpref"
|
2021-08-09 03:20:27 +00:00
|
|
|
)
|
|
|
|
|
2022-02-22 08:24:31 +00:00
|
|
|
// ConnectTLSOpts ...
|
|
|
|
type ConnectTLSOpts struct {
|
|
|
|
Host string
|
|
|
|
DBName string
|
|
|
|
ReplSet string
|
|
|
|
CaFilePath string
|
|
|
|
CertificateKeyFilePath string
|
|
|
|
CertificateKeyFilePassword string
|
|
|
|
}
|
|
|
|
|
2021-08-09 03:20:27 +00:00
|
|
|
var db *mongo.Database
|
|
|
|
|
2022-02-22 08:24:31 +00:00
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2021-08-09 03:20:27 +00:00
|
|
|
// Connect to mongo server
|
2021-10-08 08:05:13 +00:00
|
|
|
func Connect(host, user, password, dbName, mechanism, source string) (*mongo.Database, error) {
|
2021-08-09 03:20:27 +00:00
|
|
|
connectOptions := options.ClientOptions{}
|
|
|
|
// Set auth if existed
|
|
|
|
if user != "" && password != "" {
|
|
|
|
connectOptions.Auth = &options.Credential{
|
|
|
|
AuthMechanism: mechanism,
|
|
|
|
AuthSource: source,
|
|
|
|
Username: user,
|
|
|
|
Password: password,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Connect
|
|
|
|
client, err := mongo.Connect(context.Background(), connectOptions.ApplyURI(host))
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("Error when connect to MongoDB database", host, err)
|
2021-10-08 08:05:13 +00:00
|
|
|
return nil, err
|
2021-08-09 03:20:27 +00:00
|
|
|
}
|
|
|
|
|
2022-02-22 08:24:31 +00:00
|
|
|
fmt.Println(aurora.Green("*** CONNECTED TO MONGODB: " + host + " --- DB: " + dbName))
|
2021-08-09 03:20:27 +00:00
|
|
|
|
|
|
|
// Set data
|
|
|
|
db = client.Database(dbName)
|
2021-10-08 08:05:13 +00:00
|
|
|
return db, nil
|
2021-08-09 03:20:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetInstance ...
|
|
|
|
func GetInstance() *mongo.Database {
|
|
|
|
return db
|
|
|
|
}
|