title: How does middleware work in chi routing in Go and what does http.Handler argument refers to in middleware?
body: <pre class="lang-golang prettyprint-override"><code>-- routes.go --
  package main
  
  import (
      &quot;hotelsystem/pkg/config&quot;
      &quot;hotelsystem/pkg/handlers&quot;
      &quot;net/http&quot;
  
      &quot;github.com/go-chi/chi/v5&quot;
      &quot;github.com/go-chi/chi/v5/middleware&quot;
  )
  
  func routes(app *config.AppConfig) http.Handler {
      mux := chi.NewRouter()
      mux.Use(middleware.Recoverer)
      mux.Use(WriteToConsole)
      mux.Get(&quot;/&quot;, handlers.Repo.Home)
      mux.Get(&quot;/about&quot;, handlers.Repo.About)
      return mux
  
  }
  -- middleware.go --
  package main
  
  import (
      &quot;fmt&quot;
      &quot;net/http&quot;
  )
  
  func WriteToConsole(next http.Handler) http.Handler {
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
          fmt.Println(&quot;Hit the page&quot;)
          next.ServeHTTP(w, r)
      })
  }
  -- main.go --
  package main
  
  import (
      &quot;hotelsystem/pkg/config&quot;
      &quot;hotelsystem/pkg/handlers&quot;
      &quot;hotelsystem/pkg/render&quot;
      &quot;log&quot;
      &quot;net/http&quot;
  )
  
  const portNumber = &quot;:3000&quot;
  
  func main() {
      var app config.AppConfig
      tc, err := render.CreateTemplateCache()
      if err != nil {
          log.Fatal(&quot;Can't create templatecache&quot;, err)
      }
      app.TemplateCache = tc
      app.UseCache = false
      repo := handlers.NewRepo(&amp;app)
      handlers.NewHandlers(repo)
      render.NewTemplate(&amp;app)
      // http.HandleFunc(&quot;/&quot;, handlers.Repo.Home)
      // http.HandleFunc(&quot;/about&quot;, handlers.Repo.About)
      // http.ListenAndServe(portNumber, nil)
  
      srv := &amp;http.Server{
          Addr:    portNumber,
          Handler: routes(&amp;app),
      }
      err = srv.ListenAndServe()
      if err != nil {
          log.Fatal(err)
      }
  }
  </code></pre>
  <p>I am having a hard time understanding the middleware.</p>
  <p>I am using <a href="https://github.com/go-chi/chi" rel="nofollow noreferrer">chi</a> for routing.</p>
  <p>What I didn't understand is what does that (next <code>http.Handler</code>) argument in the <code>WriteToConsole</code> refers to?</p>
  <p>Does it refer to our mux router?</p>
  <p>Also when I comment down the line <code>next.ServeHTTP</code> of function writetoconsole the html is not rendered or anything? can someone explain me what does that next <code>http.Handler</code> refers to and what <code>next.serveHTTP</code> does?</p>