58 lines
1.0 KiB
Go
58 lines
1.0 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"time"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
const (
|
|
webPort = "80"
|
|
rpcPort = "5001"
|
|
mongoURL = "mongodb://mongo:27017"
|
|
gRpcPort = "50001"
|
|
)
|
|
|
|
var client *mongo.Client
|
|
|
|
type Config struct{}
|
|
|
|
func main() {
|
|
// connect to mongo
|
|
mongoClient, err := connectToMongo()
|
|
if err != nil {
|
|
log.Panic(err)
|
|
}
|
|
// create a context in order to disconnect
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
|
|
// close connection
|
|
defer func() {
|
|
if err = mongoClient.Disconnect(ctx); err != nil {
|
|
panic(err)
|
|
}
|
|
}()
|
|
|
|
client = &mongo.Client{}
|
|
}
|
|
|
|
func connectToMongo() (*mongo.Client, error) {
|
|
clientOptions := options.Client().ApplyURI(mongoURL)
|
|
clientOptions.SetAuth(options.Credential{
|
|
Username: "admin",
|
|
Password: "password",
|
|
})
|
|
|
|
client, err := mongo.Connect(context.TODO(), clientOptions)
|
|
if err != nil {
|
|
log.Println("Error connecting:", err)
|
|
return nil, err
|
|
}
|
|
|
|
return client, nil
|
|
}
|