What's the difference between:
1.
url := "https://grantpitt.com"
req, _ := http.NewRequest("Get", url, nil)
res, _ := http.DefaultClient.Do(req)
reader := strings.NewReader("")
req, _ := http.NewRequest("Get", url, reader)
res, _ := http.DefaultClient.Do(req)
req, _ := http.NewRequest("Get", url, nil)
client := &http.Client{}
res, _ := client.Do(req)
resp, err := http.Get(url)
The docs say something something about custom headers or handling between these methods. What's wierd is that methods 1-3 return '400 Bad Request' while method 4 performs as expected. Why is this? Is there some headers that don't get set in methods 1-3? How would I troubleshoot this?
CodePudding user response:
In 1,2,3 you ought to replace "Get"
with "GET"
.
In 2, the 3rd argument for NewRequest("Get", url, reader)
is used to supply the request body. Since a GET
request does not have body, it should be set to nil
instead. The body argument is useful for other methods like POST
.
4 is just a short form for the same request you do in 3.
req, _ := http.NewRequest("Get", url, nil)
gives you more control over the request, compared to http.Get(url)
, since you can set request options before sending.
CodePudding user response:
The request method should be an all uppercase "GET" rather than "Get". For why someone would prefer one method shown over another, see the docs.