I am using the official mongo driver for golang.
I am working on an HTTP server. And all of my handler function has the same pattern. All handlers are in handler/handler.go
.
client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err := client.Connect(ctx)
if err != nil {
panic(err)
}
defer client.Disconnect(ctx)
collection := client.Database("foo").Collection("bar")
What other ways are available than extracting this block to a function and calling in all the handlers?
Can I make a connection in the main.go
file and use it in all the handlers? How can I do that? I am using gorilla mux by the way.
Anything you’d like to suggest?