Home > Back-end >  Passing context in *http.request in middleware gives an error
Passing context in *http.request in middleware gives an error

Time:08-17

I am trying to pass some data to handler function through a chi middleware like this:

ctx := context.WithValue(context.Background(), int32(0), company)
next.ServeHTTP(w, r.WithContext(ctx))
return

But the next.ServeHTTP() throws this error:

interface conversion: interface {} is nil, not *chi.Context

CodePudding user response:

context.Background() gives a non-nil context and that's why the interface{} is nil error is arising. You need to use update the context embedded in request itself. Try this:

ctx := context.WithValue(r.Context(), int32(0), company)
next.ServeHTTP(w, r.WithContext(ctx))
return
  • Related