title: http: read on closed response body - httptest.NewServer
body: <p>I am trying to get to grips with testing using the httptest.NewServer and I am hitting a roadblock.</p>
  <p>In my code I am making a GET request to an external API and I want to write a test for this using httptest.NewServer.</p>
  <p>Here is my code making the request (main.go):</p>
  <pre><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;io&quot;
      &quot;io/ioutil&quot;
      &quot;log&quot;
      &quot;net/http&quot;
  )
  
  type HTTPClient interface {
      Do(req *http.Request) (*http.Response, error)
  }
  
  type NewRequest interface {
      NewRequest(method string, url string, body io.Reader) (*http.Request, error)
  }
  
  var (
      Client HTTPClient
  )
  
  func init() {
      Client = &amp;http.Client{}
  }
  
  func main() {
      url := &quot;https://httpbin.org/get&quot;
      GetData(url)
  }
  
  func GetData(url string) (*http.Response, error) {
      req, err := http.NewRequest(http.MethodGet, url, nil)
      if err != nil {
          log.Fatalln(err)
          return nil, err
      }
  
      resp, err := Client.Do(req)
  
      if err != nil {
          log.Fatalln(err)
          return nil, err
      }
  
      defer resp.Body.Close()
  
      responseBody, err := ioutil.ReadAll(resp.Body)
      if err != nil {
          log.Fatal(err)
          return nil, err
      }
  
      fmt.Println(resp.Status)
      fmt.Println(string(responseBody))
      return resp, nil
  }
  </code></pre>
  <p>When I run this it works fine.</p>
  <p>Here is my test file:</p>
  <pre><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;io/ioutil&quot;
      &quot;log&quot;
      &quot;net/http&quot;
      &quot;net/http/httptest&quot;
      &quot;testing&quot;
  )
  
  func TestYourHTTPGet(t *testing.T){
  
      ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
          fmt.Fprintln(w, `response from the mock server goes here`)
      }))
      defer ts.Close()
  
      mockServerURL := ts.URL
  
      resp, err := GetData(mockServerURL)
      if err != nil {
          fmt.Println(&quot;Error 1: &quot;, err)
      }
      defer resp.Body.Close()
  
      responseBody, err := ioutil.ReadAll(resp.Body)
      if err != nil {
          log.Fatal(&quot;Error 2: &quot;, err)
      }
  
      fmt.Println(resp.Status)
      fmt.Println(string(responseBody))
  }
  
  </code></pre>
  <p>When I run <code>go test</code> I receive the error: <code>http: read on closed response body</code>. If I remove <code>defer resp.Body.Close()</code> from <code>main.go</code> the test passes correctly.</p>
  <p>I am not sure why this is happening and was hoping that someone could explain what is going on here?</p>