From 02a12f0e68cff63874d7d904176196dfae4343cb Mon Sep 17 00:00:00 2001 From: Christian Hoffmeister Date: Tue, 26 Apr 2022 10:01:51 +0200 Subject: [PATCH] Fix metadata client error detection (#193) --- hcloud/metadata/client.go | 11 ++++++++--- hcloud/metadata/client_test.go | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/hcloud/metadata/client.go b/hcloud/metadata/client.go index c56f1b94..a95fb10d 100644 --- a/hcloud/metadata/client.go +++ b/hcloud/metadata/client.go @@ -1,6 +1,7 @@ package metadata import ( + "fmt" "io/ioutil" "net" "net/http" @@ -71,12 +72,16 @@ func (c *Client) get(path string) (string, error) { if err != nil { return "", err } - body, err := ioutil.ReadAll(resp.Body) + defer resp.Body.Close() + bodyBytes, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } - resp.Body.Close() - return string(body), nil + body := string(bodyBytes) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return body, fmt.Errorf("response status was %d", resp.StatusCode) + } + return body, nil } // IsHcloudServer checks if the currently called server is a hcloud server by calling a metadata endpoint diff --git a/hcloud/metadata/client_test.go b/hcloud/metadata/client_test.go index 001e76ed..ba1e59e2 100644 --- a/hcloud/metadata/client_test.go +++ b/hcloud/metadata/client_test.go @@ -34,6 +34,24 @@ func newTestEnv() testEnv { } } +func TestClient_Base(t *testing.T) { + env := newTestEnv() + env.Mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("ok")) + }) + env.Mux.HandleFunc("/not-found", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(404) + w.Write([]byte("not found")) + }) + + if body, err := env.Client.get("/ok"); assert.NoError(t, err) { + assert.Equal(t, "ok", body) + } + if body, err := env.Client.get("/not-found"); assert.EqualError(t, err, "response status was 404") { + assert.Equal(t, "not found", body) + } +} + func TestClient_IsHcloudServer(t *testing.T) { env := newTestEnv() env.Mux.HandleFunc("/hostname", func(w http.ResponseWriter, r *http.Request) {