Extract logic of executing an HTTP request
Same logic is used twice, now it's extracted
into a helper function. This is especially
important since this helper function makes
sure that the response is properly close which
can prevent future bugs.
@@ -214,55 +214,52 @@ func (v *virtHandlerConn) Pod() (pod *v1.Pod, err error) {
return v.pod, err
}
-func (v *virtHandlerConn) Put(url string, body io.ReadCloser) error {
- req, err := http.NewRequest(http.MethodPut, url, body)
- if err != nil {
- return err
- }
-
+func (v *virtHandlerConn) doRequest(req *http.Request) (response string, err error) {
resp, err := v.httpClient.Do(req)
if err != nil {
- return err
+ return
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
- return fmt.Errorf("unexpected return code %s", resp.Status)
+ return "", fmt.Errorf("unexpected return code %d (%s)", resp.StatusCode, resp.Status)
}
- _, err = io.ReadAll(resp.Body)
+ responseBytes, err := io.ReadAll(resp.Body)
if err != nil {
- return fmt.Errorf("cannot read get body %s", resp.Status)
+ return "", fmt.Errorf("cannot read response body %v", err)
}
- return nil
+ return string(responseBytes), nil
}
-func (v *virtHandlerConn) Get(url string) (string, error) {
- req, err := http.NewRequest(http.MethodGet, url, nil)
+func (v *virtHandlerConn) Put(url string, body io.ReadCloser) error {
+ req, err := http.NewRequest(http.MethodPut, url, body)
if err != nil {
- return "", err
+ return err
}
- req.Header.Add("Accept", "application/json")
- resp, err := v.httpClient.Do(req)
+ _, err = v.doRequest(req)
if err != nil {
- return "", err
+ return err
}
- if resp.StatusCode < 200 || resp.StatusCode > 299 {
- return "", fmt.Errorf("unexpected return code %s", resp.Status)
+ return nil
}
- defer resp.Body.Close()
- responseData, err := io.ReadAll(resp.Body)
+func (v *virtHandlerConn) Get(url string) (string, error) {
+ req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
- return "", fmt.Errorf("cannot read get body %s", resp.Status)
+ return "", err
}
- responseString := string(responseData)
+ req.Header.Add("Accept", "application/json")
+ response, err := v.doRequest(req)
+ if err != nil {
+ return "", err
+ }
- return responseString, nil
+ return response, nil
}
func (v *virtHandlerConn) GuestInfoURI(vmi *virtv1.VirtualMachineInstance) (string, error) {
