title: GoLang - Passing nil to function that accepts an interface
body: <p>I stumbled accross something that threw me for a loop in golang recently.</p>
  
  <pre><code>package main
  
  import (
      "net/http"
      "bytes"
      "fmt"
      "io/ioutil"
  )
  
  func createRequest(method, uri string, data *bytes.Buffer) string {
      req, err := http.NewRequest(method, uri, data)
      if err != nil {
         return ""
      }
      req.Close = true
      client := &amp;http.Client{}
      resp, err := client.Do(req)
      if err != nil {
         return ""
      }
      defer resp.Body.Close()
      respBody, err := ioutil.ReadAll(resp.Body)
      if err != nil {
          return ""
      }
      return string(respBody)
  }
  
  func createRequestNoBody(method, uri string) string {
      req, err := http.NewRequest(method, uri, nil)
      if err != nil {
         return ""
      }
      req.Close = true
      client := &amp;http.Client{}
      resp, err := client.Do(req)
      if err != nil {
         return ""
      }
      defer resp.Body.Close()
      respBody, err := ioutil.ReadAll(resp.Body)
      if err != nil {
          return ""
      }
      return string(respBody)
  }
  
  func main() {
     data := createRequestNoBody("GET", "http://google.com")
     if len(data) != 0 {
        fmt.Println("First Request Ok")
     }
     data = createRequest("GET", "https://google.com", nil)
     if len(data) != 0 {
        fmt.Println("Second Request OK")
     }
  }
  </code></pre>
  
  <p>This code works in the <code>createRequestNoBody</code> function when nil is passed directly to <code>http.NewRequest</code> but it produces a panic when calling <code>createRequest</code> with the <code>*bytes.Buffer</code> set to <code>nil</code> in the calling function.</p>
  
  <p>The NewRequest function in the http library has the following prototype:</p>
  
  <p><code>func NewRequest(method, urlStr string, body io.Reader) (*Request, error)</code></p>
  
  <p>Where <code>io.Reader</code> is an interface. </p>
  
  <p>I'm not sure why the nil being passed through a variable would cause <code>body</code> in NewRequest to become non nil.</p>
  
  <p>Can anyone explain why <code>createRequest</code> method results in a panic? How is the nil parameter at <code>data = createRequest("GET", "https://google.com", nil)</code> becoming non nil inside of the <code>NewRequest</code> method?</p>