title: Go closure deadlock
body: <p>Trying to mock http response in Go test. The code snippet below never terminates if I run it with </p>
  
  <blockquote>
    <p>go test example.com/auth/...</p>
  </blockquote>
  
  <pre><code>package auth_test
  import (
      "testing"
      "net/http/httptest"
      "net/http"
  )
  
  func TestAuthorization(t *testing.T) {
      t.Log("Should return 401 when Gateway returns 401")
      {
          url := oneOffUrlWithResponseCode(http.StatusUnauthorized)
          request, _ := http.NewRequest("GET", url, nil)
          response, _ := http.DefaultClient.Do(request)
  
          if response.StatusCode != http.StatusUnauthorized {
              t.Fatalf("Response should be 401 (Unauthorized)")
          }
      }
  }
  
  func oneOffUrlWithResponseCode(responseCode int) string {
      var server *httptest.Server
      server = httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
          defer server.Close()
          response.WriteHeader(responseCode)
      }))
      return server.URL
  }
  </code></pre>
  
  <p>However, if I comment out this line </p>
  
  <blockquote>
    <p>defer server.Close()</p>
  </blockquote>
  
  <p>everything works fine. </p>
  
  <p>Ideally, I do not want to "leak" *httptest.Server outside of oneOffUrlWithResponseCode function and obviously close it after first request. </p>
  
  <p>Why it never terminates? What am I doing wrong? What is the right thing to do?</p>