timetable-mgr/src/dbAccess/client.go

56 lines
1.2 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 00:25:13 +01:00
"git.fjla.uk/owlboard/mq-client/helpers"
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 {
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 00:25:13 +01:00
helpers.Log("Error connecting to database", 4)
} else {
helpers.Log("Connected to Database", 1)
}
return client
}