title: Golang *bytes.Buffer nil causes fatal error
body: <p>I had the same issue as <a href="https://github.com/golang/go/issues/26666" rel="nofollow noreferrer">https://github.com/golang/go/issues/26666</a> because I have a wrap function for my http requests. </p>
  
  <p>Sometimes I need to request:</p>
  
  <pre><code>body := new(bytes.Buffer)
  json.NewEncoder(body).Encode(h)
  req("POST", "http://example.com", body)
  </code></pre>
  
  <p>And sometimes it's simply:</p>
  
  <pre><code>req("GET", "http://example.com", nil)
  runtime error: invalid memory address or nil pointer dereference
  </code></pre>
  
  <p>I ended up with:</p>
  
  <pre><code>req("GET", "http://example.com", new(bytes.Buffer))
  </code></pre>
  
  <p><strong>But I'm not sure if it's the right thing to do.</strong></p>
  
  <p>The function:</p>
  
  <pre><code>func req(method string, url string, body *bytes.Buffer) int {
  req, err := http.NewRequest(method, url, body)
  req.Header.Set("Content-Type", "application/json")
  req.SetBasicAuth(user, psw)
  resp, err := client.Do(req)
  checkErr(err)
  if resp.StatusCode &gt; 500 {
      time.Sleep(30 * time.Second)
      resp, err = client.Do(req)
      checkErr(err)
  }
  defer resp.Body.Close()
  return resp.StatusCode
  }
  </code></pre>
  
  <p><strong>Updated function:</strong></p>
  
  <pre><code>func req(method string, url string, body io.Reader) int {
      req, err := http.NewRequest(method, url, body)
      req.Header.Set("Content-Type", "application/json")
      req.SetBasicAuth(user, psw)
      resp, err := client.Do(req)
      checkErr(err)
      defer resp.Body.Close()
      if resp.StatusCode &gt;= 500 {
          time.Sleep(30 * time.Second)
          req, err := http.NewRequest(method, url, body)
          req.Header.Set("Content-Type", "application/json")
          req.SetBasicAuth(user, psw)
          resp, err := client.Do(req)
          checkErr(err)
          defer resp.Body.Close()
      }
      return resp.StatusCode
  }
  
  func checkErr(err error) {
      if err != nil {
          log.Fatal(err)
      }
  }
  </code></pre>