How to pass r.Context() to DB query from middleware?


I have created a middleware.

func ContextTimeOut(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		contex, cancel := context.WithTimeout(r.Context(), 3*time.Second)
		defer cancel()

		next.ServeHTTP(w, r.WithContext(contex))

Now I need to use this context in db.QueryContext()

func (a *Handler) AddHandler(w http.ResponseWriter, r *http.Request) {
   .... get data from r ....
   ..... validate the data ....
    a.repo.Add(r, validatedData)

I have to pass it as a parameter every time. Without passing this as a function parameter, can I keep it as a global variable? How do I do it?

From the above example, I want to access it directly in the repo.

No, it may become obsolete, or you may need multiple contexts, it could be accessed from the “wrong” go routine. You could define a new interface for your contextual handlers that accepts a context and pass the desired context.

Maybe your handler just get r.Context and pass that to db.

gin puts all the request/response related info in its own context and defines its handlers to just accept a gin context.

1 Like

I am using chi.
Every function that handler has, it has to pass that r.Context()
db, err := database.DatabaseContext()
Repo is handling the db request.
repo := repo.Repo { Db: db, }

These are in the main.go
Is there a way to keep the context in the repo?

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