servicemongo
This commit is contained in:
@@ -52,8 +52,29 @@ var (
|
||||
)
|
||||
|
||||
func New(database ...string) Service {
|
||||
// Reuse Connection
|
||||
mongoDBName := os.Getenv("MONGODB_DEV_MASTER")
|
||||
if len(database) > 0 {
|
||||
mongoDBName = database[0]
|
||||
}
|
||||
if dbInstance != nil {
|
||||
if database != nil {
|
||||
mongoURI := fmt.Sprintf("mongodb://%s:%s@%s:%s/%s?authSource=admin",
|
||||
userMongo, passMongo, hostMongo, portMongo, mongoDBName)
|
||||
log.Println("Connecting to MongoDB...")
|
||||
log.Println(mongoURI)
|
||||
clientOptions := options.Client().ApplyURI(mongoURI)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
client, err := mongo.Connect(ctx, clientOptions)
|
||||
if err == nil {
|
||||
log.Println("Connected to MongoDB")
|
||||
}
|
||||
if err = client.Ping(ctx, readpref.Primary()); err != nil {
|
||||
log.Println("Failed to connect to MongoDB!!!")
|
||||
log.Fatalf("Failed to connect to database: %v", err)
|
||||
}
|
||||
dbInstance.mongoDB = client.Database(mongoDBName)
|
||||
}
|
||||
return dbInstance
|
||||
}
|
||||
simrs := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Jakarta", hostSimrs, userNameSimrs, passwordSimrs, dbNameSimrs, portSimrs)
|
||||
@@ -72,10 +93,6 @@ func New(database ...string) Service {
|
||||
} else {
|
||||
log.Println("Successfully connected to the database")
|
||||
}
|
||||
mongoDBName := os.Getenv("MONGODB_DEV_MASTER")
|
||||
if len(database) > 0 {
|
||||
mongoDBName = database[0]
|
||||
}
|
||||
mongoURI := fmt.Sprintf("mongodb://%s:%s@%s:%s/%s?authSource=admin",
|
||||
userMongo, passMongo, hostMongo, portMongo, database)
|
||||
var client *mongo.Client
|
||||
|
||||
Reference in New Issue
Block a user