Go has block scope so if you create a variable in an inner scope you cannot access it in the outer scope. You would need to declare res outside your loop to access it after the loop is complete.
var res *http.Response
for i := 1; i <= 10; i++ {
res, _ = http.DefaultClient.Do(req)
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}
//This is wrong
defer res.Body.Close()
As noted above, defer res.Body.Close() above is wrong too because you should close each new body you read.
Also as noted, you should definitely be using and checking err on all your calls.
One brief and naive way I might change this:
for i := 1; i <= 10; i++ {
url := "https://uri.api.dev"
payload := strings.NewReader("param1=example&version=2")
req, err := http.NewRequest("POST", url, payload)
if err != nil {
//Specific error handling would depend on scenario
fmt.Printf("%v\n", err)
return
}
req.Header.Add("content-type", "application/x-www-form-urlencoded")
res, err := http.DefaultClient.Do(req)
if err != nil {
//Specific error handling would depend on scenario
fmt.Printf("%v\n", err)
return
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
//Specific error handling would depend on scenario
fmt.Printf("%v\n", err)
return
}
fmt.Println(string(body))
res.Body.Close()
}
Something to think about here. You are wanting to make 10 calls to an API in serial. A natural extension to that is to do the test in parallel or at least concurrently using the 'go' keyword. For that you can't share variables across your loop iterations. Something like:
for i := 1; i <= 10; i++ {
//Where testApi is the whole process encapsulated for one iteration
go testApi()
}
Finally, don't prematurely optimize. Variables with restricted scope will prevent bugs and maintenance headaches long term.
Hope this helps.
Ninja Edit:
Do not make loops start at a non-zero number without a good reason, this is probably the most common way to think about your loop below. The 1 - 10 version feels very VB/VB.Net.
for i := 0; i < 10; i++ {
//Where testApi is the whole process encapsulated for one iteration
go testApi()
}
http.Requestwith a new payload,Do()the request, handle the response.