I stumbled accross something that threw me for a loop in golang recently.
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 := &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 := &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")
}
}
This code works in the createRequestNoBody
function when nil is passed directly to http.NewRequest
but it produces a panic when calling createRequest
with the *bytes.Buffer
set to nil
in the calling function.
The NewRequest function in the http library has the following prototype:
func NewRequest(method, urlStr string, body io.Reader) (*Request, error)
Where io.Reader
is an interface.
I'm not sure why the nil being passed through a variable would cause body
in NewRequest to become non nil.
Can anyone explain why createRequest
method results in a panic? How is the nil parameter at data = createRequest("GET", "https://google.com", nil)
becoming non nil inside of the NewRequest
method?