title: Memory leak from client.Do()
body: <p>The <code>getAPIData</code> function is for getting string of HTML, and it need to be called every 5 seconds. I checked memory usage with the <code>runtime.ReadMemStats</code> function.</p>
  <p>As the output below shows, the memory goes up slowly but never goes down.</p>
  <pre><code>Alloc = 1 MiB   TotalAlloc = 2 MiB      Sys = 71 MiB    NumGC = 1
  ...
  Alloc = 3 MiB   TotalAlloc = 4 MiB      Sys = 71 MiB    NumGC = 1
  ...
  Alloc = 3 MiB   TotalAlloc = 6 MiB      Sys = 71 MiB    NumGC = 2
  Alloc = 2 MiB   TotalAlloc = 7 MiB      Sys = 71 MiB    NumGC = 3
  ...
  Alloc = 3 MiB   TotalAlloc = 9 MiB      Sys = 71 MiB    NumGC = 3
  ...
  Alloc = 3 MiB   TotalAlloc = 10 MiB     Sys = 71 MiB    NumGC = 4
  </code></pre>
  <p>I made sample code of my problem. What should I do to fix that memory leak?</p>
  <pre><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;io/ioutil&quot;
      &quot;net/http&quot;
      &quot;runtime&quot;
      &quot;time&quot;
  )
  
  func getAPIData() (string, error) {
      req, err := http.NewRequest(&quot;GET&quot;, &quot;https://google.com/&quot;, nil)
      if err != nil {
          //fmt.Println(err.Error())
          return &quot;&quot;, err
          //panic(err)
      }
      req.Header.Add(&quot;User-Agent&quot;, &quot;Mozilla/5.0&quot;)
  
      client := &amp;http.Client{Timeout: 3 * time.Second}
      resp, err := client.Do(req) // cuase of memory leak
      if err != nil {
          fmt.Println(err.Error())
          return &quot;&quot;, err
          //panic(err)
      }
      defer resp.Body.Close()
  
      bytes, err2 := ioutil.ReadAll(resp.Body)
      if err2 != nil {
          fmt.Println(err2.Error())
          return &quot;&quot;, err2
          //panic(err)
      }
      return string(bytes), nil
  }
  
  func PrintMemUsage() {
      var m runtime.MemStats
      runtime.ReadMemStats(&amp;m)
  
      fmt.Printf(&quot;Alloc = %v MiB&quot;, bToMb(m.Alloc))
      fmt.Printf(&quot;\tTotalAlloc = %v MiB&quot;, bToMb(m.TotalAlloc))
      fmt.Printf(&quot;\tSys = %v MiB&quot;, bToMb(m.Sys))
      fmt.Printf(&quot;\tNumGC = %v\n&quot;, m.NumGC)
  }
  
  func bToMb(b uint64) uint64 {
      return b / 1024 / 1024
  }
  func main() {
      for range time.Tick(5 * time.Second) {
          _, _ = getAPIData()
          PrintMemUsage()
      }
  }
  </code></pre>