Skip to content

Commit

Permalink
Fix metadata client error detection (#193)
Browse files Browse the repository at this point in the history
  • Loading branch information
choffmeister authored Apr 26, 2022
1 parent cf8f35d commit 02a12f0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
11 changes: 8 additions & 3 deletions hcloud/metadata/client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package metadata

import (
"fmt"
"io/ioutil"
"net"
"net/http"
Expand Down Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions hcloud/metadata/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 02a12f0

Please sign in to comment.