Search code examples
mongodbapigogoland

MongoDB connection request stuck on core.DataProvider.Connect() call


Hello I am trying to establish a connection to my local mongodb database but the when the core.DataProvider.Connect() function is called it is stuck and the execution does not proceed no error no nothing I tried the program with a cloud database and it works and I also tried it on my other computer with same program same env variables and it works with no problem I traced the program and it seems it is getting stuck on the session.Ping() call in DialWithInfo function is it a problem with my PC or is it a bug?

full function

func initDatabase() {

    // create mongo db adapter
    mongoAdapter := &mongoutil.DataProvider{}

    // set mongo addresses
    if mongoAddresses, hasMongoAddresses := os.LookupEnv("MONGO_ADDRESSES"); hasMongoAddresses {
        mongoAdapter.Addresses = strings.Split(mongoAddresses, ",")
    } else {
        log.Fatal("Mongo addresses must be specified with environment variable MONGO_ADDRESSES.")
    }

    // set mongo users database
    if database, hasDatabase := os.LookupEnv("MONGO_DB_NAME"); hasDatabase {
        mongoAdapter.Database = database
    } else {
        log.Fatal("Mongo database name must be provided with the environment variable MONGO_DB_NAME.")
    }

    // set mongo users database
    if authDatabase, hasAuthDatabase := os.LookupEnv("MONGO_AUTH_DB"); hasAuthDatabase {
        mongoAdapter.AuthDatabase = authDatabase
    } else {
        log.Info("Mongo users database name should be provided with the environment variable MONGO_AUTH_DB.")
    }

    // set mongo username
    if mongoUserName, hasUsername := os.LookupEnv("MONGO_USER_NAME"); hasUsername {
        mongoAdapter.Username = mongoUserName
    } else {
        log.Info("Mongo user name should be provided with the environment variable MONGO_USER_NAME.")
    }

    // set mongo password
    if mongoPassword, hasPassword := os.LookupEnv("MONGO_PASSWORD"); hasPassword {
        mongoAdapter.Password = mongoPassword
    } else {
        log.Info("Mongo password should be provided with the environment variable MONGO_PASSWORD.")
    }

    mongoAdapter.Collections = availableCollections

    dbInitErr := mongoAdapter.Init()
    if dbInitErr != nil {
        log.Fatal(dbInitErr.Message)
        os.Exit(dbInitErr.Code)
    }

    core.DataProvider = mongoAdapter

    // connecting to the database
    dbConnErr := core.DataProvider.Connect()
    if dbConnErr != nil {
        log.Fatal(dbConnErr.Message)
        os.Exit(dbConnErr.Code)
    }
    log.Info("Database connection is established successfully.")
}

Solution

  • Just to provide an example of what suggested by @icza, you can use this code:

    package main
    
    import (
        "context"
        "time"
    
        "go.mongodb.org/mongo-driver/mongo"
        "go.mongodb.org/mongo-driver/mongo/options"
        "go.mongodb.org/mongo-driver/mongo/readpref"
    )
    
    var (
        ctx    context.Context
        cancel context.CancelFunc
    )
    
    func main() {
        ctx, cancel = context.WithTimeout(context.Background(), 20*time.Second)
        defer cancel()
    
        // set MongoDB connection
        clientOptions := options.Client().ApplyURI("mongodb://root:root@localhost:27017")
        mongoClient, err := mongo.Connect(ctx, clientOptions)
        if err != nil {
            panic(err)
        }
        defer mongoClient.Disconnect(ctx)
    
        // ping the MongoDB
        err = mongoClient.Ping(ctx, readpref.Primary())
        if err != nil {
            panic(err)
        }
    }
    

    Here, you can see how to set up a MongoDB connection that points to a local instance of MongoDB. Then, it tries pinging it just to be sure that the MongoDB is up & running.

    The command used to launch the MongoDB with Docker is: docker run -d -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=root mongo:latest

    Hope this helps you to solve your issue, let me know!