timetable-mgr/src/dbAccess/client.go

69 lines
1.6 KiB
Go
Raw Normal View History

2023-07-17 12:48:36 +01:00
package dbAccess
2023-07-15 22:32:46 +01:00
import (
2023-07-18 14:09:28 +01:00
"git.fjla.uk/owlboard/mq-client/log"
2023-07-15 23:00:48 +01:00
2023-07-15 22:32:46 +01:00
"context"
"fmt"
2023-07-18 00:25:13 +01:00
"os"
"time"
2023-07-15 22:32:46 +01:00
2023-07-18 00:25:13 +01:00
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
// "go.mongodb.org/mongo-driver/mongo/readpref"
2023-07-15 22:32:46 +01:00
)
2023-07-18 00:25:13 +01:00
// Generate DB Url
var dbUri string = getDbUri()
func getDbUri() string {
2023-07-18 14:09:28 +01:00
log.Msg.Debug("Fetching DB Access details")
2023-07-18 00:25:13 +01:00
var dbHost string = os.Getenv("OWL_DB_HOST")
if dbHost == "" {
dbHost = "localhost"
}
var dbPort string = os.Getenv("OWL_DB_PORT")
if dbPort == "" {
dbPort = "27017"
}
var dbUser string = os.Getenv("OWL_DB_USER")
if dbUser == "" {
dbUser = "owl"
}
var dbPass string = os.Getenv("OWL_DB_PASS")
if dbPass == "" {
dbPass = "twittwoo"
}
var uri = "mongodb://" + dbUser + ":" + dbPass + "@" + dbHost + ":" + dbPort
return uri
}
2023-07-15 23:00:48 +01:00
// Provide the DB Connection to other functions
var MongoClient (*mongo.Client) = initDataAccess()
2023-07-15 22:32:46 +01:00
2023-07-15 23:00:48 +01:00
// Initialise the DB Connection
2023-07-18 00:25:13 +01:00
func initDataAccess() *mongo.Client {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(dbUri))
if err != nil {
2023-07-15 22:32:46 +01:00
fmt.Println(err)
2023-07-18 14:09:28 +01:00
log.Msg.Fatal("Error connecting to database: " + err.Error())
2023-07-18 00:25:13 +01:00
} else {
2023-07-19 01:18:55 +01:00
log.Msg.Info("Database connection successful")
2023-07-18 00:25:13 +01:00
}
return client
}
2023-07-21 10:02:55 +01:00
func CloseMongoClient() {
if MongoClient != nil {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := MongoClient.Disconnect(ctx); err != nil {
log.Msg.Warn("Error disconnecting MongoDB client: " + err.Error())
} else {
log.Msg.Info("MongoDB client disconnected.")
}
}
}