Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix metadata client error detection #193

Merged
merged 1 commit into from
Apr 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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