Reputation: 725
API test has below boiler plate code.
I want to call resp.Body.Close()
even when require.Equal(ru.ts.T(), tp.expectedStatus, resp.StatusCode)
fails.
Currently i have script like below. Are there better ways to write this?
I want to avoid condition if tp.expectedStatus != resp.StatusCode
and call resp.Body.Close()
when require.Equal(ru.ts.T(), tp.expectedStatus, resp.StatusCode)
fails.
func Invoke(ip RestParams, es int) *http.Response {
client := &http.Client{}
// Initialize req using ip
resp, err := client.Do(req)
...
if tp.expectedStatus != resp.StatusCode {
resp.Body.Close()
require.Equal(ru.ts.T(), tp.expectedStatus, resp.StatusCode)
return nil
}
return resp
}
Upvotes: 1
Views: 90
Reputation: 11
You should almost always do
resp, err := client.Do(req)
if err != nil {...} // Or require.NoError(err)
defer resp.Body.Close()
http package garanties a non nil body that should be closed as soon as the error is nil.
As a side note, I think you should avoid returning the http.Response
. Unmarshal it here and return a struct model so you can handle all your technical http layer in this functio.
Upvotes: 1