Files
go-fiber-template/config/mongodb.go

69 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-01-10 21:20:45 +01:00
package config
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"time"
"gopkg.cloudyne.io/go-fiber-template/helpers"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"gopkg.in/mgo.v2/bson"
)
var Client *mongo.Client = ConnectDB()
var Database *mongo.Database = Client.Database(Getenv("MONGODB"))
func ConnectDB() *mongo.Client {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
mongoOptions := options.Client()
mongoOptions.ApplyURI(Getenv("MONGOURI"))
if mongotls := GetenvDefault("MONGOCACERT", ""); mongotls != "" {
rootCert := x509.NewCertPool()
rootCert.AppendCertsFromPEM([]byte(mongotls))
mongoOptions.SetTLSConfig(&tls.Config{
RootCAs: rootCert,
})
}
client, err := mongo.Connect(ctx, mongoOptions)
helpers.PanicIfError(err)
err = client.Ping(ctx, nil)
helpers.PanicIfError(err)
helpers.Logger.Print("Connected to MongoDB")
database := Getenv("MONGODB")
helpers.Logger.Printf("Checking for database %s", database)
databases, err := client.ListDatabaseNames(ctx, bson.M{})
helpers.PanicIfError(err)
exists := false
for _, dbname := range databases {
if dbname == database {
exists = true
break
}
}
if !exists {
panic(fmt.Errorf("error: not database with given name %s exists", database))
}
return client
}
func CheckDB() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
Client.Ping(ctx, nil)
}