title: Unit testing http handlers in golang mocking dependencies
body: <p>At the moment I try to establish best practices for unit testing go handlers.
  I need to mock dependencies, but therefore I have to be able to access / mock these dependencies.</p>
  
  <p>There I some solutions I do not want to consider like for example global variables / application state. Or having all handlers as functions of a struct holding the dependencies member variables.</p>
  
  <p>I was kind of satisfied with a solution where I injected the needed dependencies of a handler in the following way:</p>
  
  
  
  <pre class="lang-golang prettyprint-override"><code>func helloHandler(db *DbService) http.HandlerFunc {
    return func(w http.ResponseWriter, r *httpRequest) {
      // handler code goes here
    }
  }
  </code></pre>
  
  <p>Then I am able to provide this handler for routing:</p>
  
  <pre class="lang-golang prettyprint-override"><code>http.HandleFunc("/hello", helloHander(myDbService))
  </code></pre>
  
  <p>I can also test it easily:</p>
  
  <pre class="lang-golang prettyprint-override"><code>helloHandler(myDbService)(req, respRecorder)
  </code></pre>
  
  <p>But when I use for example gorilla mux (what I haven't considered from the beginning) I get another problem.</p>
  
  <p>Gorilla/mux adds extra semantics like filtering by Method (GET / POST), providing path parameters etc.</p>
  
  <p>So I should need to test the resulting gorilla router.
  But then I am again not able to inject my mock dependencies anymore.</p>
  
  <p>When I get the router back everything (dependencies) is already set up.</p>
  
  <p>But I also don't want to rebuild my Router in my tests because of DRY!</p>
  
  <p>So for now I don't really have a good solution for the problem of conveniently setting up my routes but also being able to mock the dependencies.</p>
  
  <p>Any idea?</p>