netmaker/mongoconn/mongoconn.go

68 lines
1.5 KiB
Go
Raw Normal View History

2021-03-26 00:17:52 +08:00
package mongoconn
import (
"context"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/gravitl/netmaker/servercfg"
2021-03-26 00:17:52 +08:00
)
var Client *mongo.Client
var NodeDB *mongo.Collection
var NetworkDB *mongo.Collection
2021-03-26 00:17:52 +08:00
var user string
var pass string
var host string
var port string
var opts string
func setVars() {
user = servercfg.GetMongoUser()
pass = servercfg.GetMongoPass()
host = servercfg.GetMongoHost()
port = servercfg.GetMongoPort()
opts = servercfg.GetMongoOpts()
2021-03-26 00:17:52 +08:00
}
func ConnectDatabase() {
// Set client options
setVars()
clientOptions := options.Client().ApplyURI( "mongodb://" +
user + ":" +
pass + "@" +
host + ":" +
port +
opts )
// Connect to MongoDB
2021-05-06 04:42:17 +08:00
log.Println("Connecting to MongoDB at " + host + ":" + port + "...")
2021-03-26 00:17:52 +08:00
client, err := mongo.Connect(context.TODO(), clientOptions)
Client = client
if err != nil {
2021-05-06 04:42:17 +08:00
log.Println("Error encountered connecting to MongoDB. Terminating.")
2021-03-26 00:17:52 +08:00
log.Fatal(err)
}
// Check the connection
err = Client.Ping(context.TODO(), nil)
if err != nil {
2021-05-06 04:42:17 +08:00
log.Println("Error encountered pinging MongoDB. Terminating.")
2021-03-26 00:17:52 +08:00
log.Fatal(err)
}
NodeDB = Client.Database("netmaker").Collection("nodes")
NetworkDB = Client.Database("netmaker").Collection("networks")
2021-03-26 00:17:52 +08:00
2021-05-06 04:42:17 +08:00
log.Println("MongoDB Connected.")
2021-03-26 00:17:52 +08:00
}
// ErrorResponse : This is error model.
type ErrorResponse struct {
StatusCode int `json:"status"`
ErrorMessage string `json:"message"`
}