-2

I am writing a Go app that will need to connect to a MongoDB for persistence.

I want the client connection to be shared (so that I do not have to re-initialize/create the client connection for each operation). (the program will expose a restful API so each operation will more or less correspond to an HTTP request).

So (since this is still a draft project and still a single file application) I though going about it like this.

a) declare a package scoped pointer var for the client connection

var mongoClient *mongo.Client 

b) initialize it in main

clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
mongoClient, err := mongo.Connect(ctx, clientOptions)

and then

c) use it in a handler function e.g.

collection := mongoClient.Database("mydb").Collection("mycollection")

The problem is that the program does not compile with the error:

mongoClient declared and not used

My workaround was to either

A. add the following line within main() after the variables initialization

    mongoClient, err := mongo.Connect(ctx, clientOptions)
    _ = mongoClient

OR

B. use throwaway variable for the error so that I have only var initialization (and not declaration as follows

mongoClient, _ = mongo.Connect(ctx, clientOptions)

but that prevents me from the error handling.

Is any other (better) practice / established pattern for this problem? Is this the right practice?

Flimzy
  • 68,325
  • 15
  • 126
  • 165
pkaramol
  • 12,615
  • 22
  • 104
  • 231

1 Answers1

4

In this line:

mongoClient, err := mongo.Connect(ctx, clientOptions)

Remember that := declares and initializes a new variable. So you're creating a new, local variable named mongoClient here, which shadows the global; the global remains unchanged. Change this instead to:

var err error
mongoClient, err = mongo.Connect(ctx, clientOptions)
Adrian
  • 38,231
  • 5
  • 90
  • 87