57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
package database
|
|
|
|
import (
|
|
"antrian-operasi/internal/config"
|
|
"context"
|
|
"crypto/tls"
|
|
"fmt"
|
|
"log"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
func (s *service) addMongoDB(name string, config config.DatabaseConfig) error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), config.Timeout)
|
|
defer cancel()
|
|
|
|
// Build MongoDB URI with authentication and TLS options
|
|
uri := fmt.Sprintf("mongodb://%s:%s@%s:%d/%s",
|
|
config.Username,
|
|
config.Password,
|
|
config.Host,
|
|
config.Port,
|
|
config.Database,
|
|
)
|
|
|
|
// Configure client options with security settings
|
|
clientOptions := options.Client().ApplyURI(uri)
|
|
|
|
// Set TLS configuration if needed
|
|
if config.RequireSSL {
|
|
clientOptions.SetTLSConfig(&tls.Config{
|
|
InsecureSkipVerify: config.SSLMode == "require",
|
|
MinVersion: tls.VersionTLS12,
|
|
})
|
|
}
|
|
|
|
// Set connection timeout
|
|
clientOptions.SetConnectTimeout(config.ConnectTimeout)
|
|
clientOptions.SetServerSelectionTimeout(config.Timeout)
|
|
|
|
client, err := mongo.Connect(ctx, clientOptions)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to connect to MongoDB: %w", err)
|
|
}
|
|
|
|
// Ping to verify connection
|
|
if err := client.Ping(ctx, nil); err != nil {
|
|
return fmt.Errorf("failed to ping MongoDB: %w", err)
|
|
}
|
|
|
|
s.mongoClients[name] = client
|
|
log.Printf("Successfully connected to MongoDB: %s", name)
|
|
|
|
return nil
|
|
}
|