title: How to pass context in golang request to middleware
body: <p>I am trying to understand how the context introduced in Golang 1.7 works and what would be the appropriate way to pass it to middleware and to a <code>HandlerFunc</code>. Should the context get initialized in the main function and passed to the <code>checkAuth</code> function then? And how to pass it to <code>Hanlder</code> and the <code>ServeHTTP</code> function?
  I read <a href="https://blog.golang.org/context" rel="noreferrer">Go concurrency patterns</a> and <a href="https://medium.com/@cep21/how-to-correctly-use-context-context-in-go-1-7-8f2c0fafdf39#.7dcv2847z" rel="noreferrer">How to use Context</a> but I struggle to adapt those patterns to my code.</p>
  
  <pre><code>func checkAuth(authToken string) util.Middleware {
      return func(h http.Handler) http.Handler {
          return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
              if r.Header.Get("Auth") != authToken {
                  util.SendError(w, "...", http.StatusForbidden, false)
                  return
              }
              h.ServeHTTP(w, r)
          })
      }
  }
  
  // Handler is a struct
  type Handler struct {
      ...
      ...
  }
  
  // ServeHTTP is the handler response to an HTTP request
  func (h *HandlerW) ServeHTTP(w http.ResponseWriter, r *http.Request) {
      decoder := json.NewDecoder(r.Body)
  
      // decode request / context and get params
      var p params
      err := decoder.Decode(&amp;p)
      if err != nil {
         ...
          return
      }
  
      // perform GET request and pass context
      ...
  
  
  }
  
  
  func main() {
      router := mux.NewRouter()
  
      // How to pass context to authCheck?
      authToken, ok := getAuthToken()
      if !ok {
          panic("...")
      }
      authCheck := checkAuth(authToken)
  
      // initialize middleware handlers
      h := Handler{
         ...
     } 
  
     // chain middleware handlers and pass context
     router.Handle("/hello", util.UseMiddleware(authCheck, Handler, ...))
  }
  </code></pre>