+2
-2
@@ -17,13 +17,13 @@ import (
|
||||
|
||||
func main() {
|
||||
mongoURI := getEnv("MONGO_URI", "mongodb://localhost:27017")
|
||||
dbName := getEnv("MONGO_DB", "vantage")
|
||||
|
||||
if os.Getenv("GRPC_HOST") == "" {
|
||||
log.Fatal("GRPC_HOST is required (host:port agents dial for gRPC)")
|
||||
}
|
||||
|
||||
if err := db.Connect(mongoURI, dbName); err != nil {
|
||||
// DB name comes from the MONGO_URI path; "vantage" is the fallback.
|
||||
if err := db.Connect(mongoURI, "vantage"); err != nil {
|
||||
log.Fatalf("failed to connect to MongoDB: %v", err)
|
||||
}
|
||||
log.Println("connected to MongoDB")
|
||||
|
||||
@@ -2,16 +2,30 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
||||
"go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring"
|
||||
)
|
||||
|
||||
var Client *mongo.Client
|
||||
var Database *mongo.Database
|
||||
|
||||
func Connect(uri, dbName string) error {
|
||||
// Connect resolves the database name from the URI path (e.g.
|
||||
// mongodb://host:27017/vantage), falling back to fallbackDB when the URI names
|
||||
// none, so a bare URI still works without a separate MONGO_DB env var.
|
||||
func Connect(uri, fallbackDB string) error {
|
||||
cs, err := connstring.ParseAndValidate(uri)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse MONGO_URI: %w", err)
|
||||
}
|
||||
dbName := cs.Database
|
||||
if dbName == "" {
|
||||
dbName = fallbackDB
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user