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) {