Using the same context.Background() for all calls?

I have a (production) REST API written in golang1.13 with gorilla/mux v1.7.3.

I don’t really need (at the moment) requests cancellation/with a timeout so every time I needed to pass a context to some function - I just use the same ctx variable in my package, that is defined in the func init() as:

ctx := context.Background()

For example, I have a package that is using the Azure SDK to perform some functionalities. Every method that the Azure SDK has, I need to pass a context, so I pass the ctx above.

So I have a REST API that every request sometimes uses the above functionalities.

  1. I don’t understand if this is bad/good at all, or considered good/bad practice.
  2. And the most important question - this currently seems to work. Can it go wrong?

As can be seen from the source code of context.Background it is just an instance of

type emptyCtx int

which defaults to 0. Such a context does nothing, just as the documentation tells us.

Note that there is context.TODO:

Code should use context.TODO when it’s unclear which Context to use

Even though context.Background and context.TODO are instances of the same type, using context.TODO seems to be more appropriate for your use case.

I don’t think using any of these two can go wrong. They just do nothing.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.