Manually deleting val from context map using Gorilla middleware

36 views Asked by At

Do I need to do this:

  r.Use(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      muxctx.Set(r, "req-res-ctx", &mw.Ctx{
        Log: vbl.Stdout.Child(&map[string]interface{}{}),
      })
      defer func() {   
        muxctx.Delete(r, "req-res-ctx") // <-------------------- HERE
      }()
      next.ServeHTTP(w, r)
    })
  })

or does the context magically auto-delete the entry? I would think that I would also need to do this:

      defer func() {   
        muxctx.Delete(r) // delete ref to request too?
      }()
1

There are 1 answers

0
Alexander Mills On

Looks like we should use muxctx.Clear(r) like so:

  r.Use(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      muxctx.Set(r, "req-res-ctx", &mw.Ctx{
        Log: vbl.Stdout.Child(&map[string]interface{}{}),
      })
      defer func() {
        muxctx.Delete(r, "req-res-ctx")
        muxctx.Clear(r)  // <---------------HERE
      }()
      next.ServeHTTP(w, r)
    })
  })

I also read that we should use the ctx := r.Context() but this API seems confusing and not sure if it's an improvement.