I use semi-code here just to show my intention of whats going on in code and not complicating things here in the question.
I have a main.go file that calls a method that connects to mongoDB database:
mStore := store.NewMongoStore()
In NewMongoStore I have context that client.Connect uses to connect to database:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
Now in main.go I pass the store to my router controller file this way:
routes.GenericRoute(router, mStore)
In GenericRoute I get the mStore and pass it to function handlers:
func GenericRoute(router *gin.Engine, mStore store.Store) {
router.POST("/users", controllers.CreateUser(mStore))
}
Now in CreateUser I again create a context as below to insert document into MongoDB:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
insertedId, err := repo.CreateUser(ctx, newUser{"John", "Doe"})
Here I passed context to createUser to insert a new document.
As you see in some parts I have passed context and in some parts I did not. I really do not have any idea what I should do? What is the correct way to work with contexts? Should I always pass context around or it is totally ok to create new contexts like this to not pass context in method parameters.
What is the best practice for this kind of coding? And which one is better from performance point of view?