gonegroni

Negroni: passing context from middleware to handlers


I'm trying to add a Gorilla Session to the Request Context in a Negroni middleware handler so that I can access it in my Gorilla Mux handlers. Here's a stripped down version of my code:

// Session Middleware function
func sessMid(w http.ResponseWriter, r *http.Request, next 
http.HandlerFunc) {
  ctx := r.Context()
  s, _ := store.Get(r, "user") // store is a CookieStore
  ctx = context.WithValue(ctx, "example", s)

  if !loggedIn() {
    http.Redirect(w, r, "/login", http.StatusFound)
  }

  next(w, r.WithContext(ctx))
}

// Page handler
func pgHandler(w http.ResponseWriter, r *http.Request) {
  ctx := r.Context()
  s, ok := ctx.Value("example").(*sessions.Session)
  // ok returns false here, meaning that the session was not returned successfully.
}

Hopefully that makes sense. Can anyone point me to what I'm doing wrong?


Solution

  • The Redirect statement is receiving the original request without the new context that contains the session. The WithContext(ctx) function needs to be used here as well:

    // Session Middleware function
    func sessMid(w http.ResponseWriter, r *http.Request, next 
    http.HandlerFunc) {
      ctx := r.Context()
      s, _ := store.Get(r, "user") // store is a CookieStore
      ctx = context.WithValue(ctx, "example", s)
    
      if !loggedIn() {
        // Make sure to add the context to the request sent in the Redirect
        http.Redirect(w, r.WithContext(ctx), "/login", http.StatusFound)
      }
    
      next(w, r.WithContext(ctx))
    }
    

    Thanks to @jmaloney for sending me down the right path.