Skip to content

Commit

Permalink
fix(exp): configure response headers before sending them (#473)
Browse files Browse the repository at this point in the history
Ensure the headers are configured before we set the status code and send
the headers.
  • Loading branch information
jooola committed Jun 25, 2024
1 parent baf8806 commit 07d4a35
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
5 changes: 4 additions & 1 deletion hcloud/exp/mockutils/mockutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,22 @@ func Handler(t *testing.T, requests []Request) http.HandlerFunc {
expected.Want(t, r)
}

w.WriteHeader(expected.Status)
switch {
case expected.JSON != nil:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(expected.Status)
if err := json.NewEncoder(w).Encode(expected.JSON); err != nil {
t.Fatal(err)
}
case expected.JSONRaw != "":
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(expected.Status)
_, err := w.Write([]byte(expected.JSONRaw))
if err != nil {
t.Fatal(err)
}
default:
w.WriteHeader(expected.Status)
}

index++
Expand Down
13 changes: 13 additions & 0 deletions hcloud/exp/mockutils/mockutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,33 @@ func TestHandler(t *testing.T) {
Status: 400,
JSONRaw: `{"error": "failed"}`,
},
{
Method: "GET", Path: "/",
Status: 503,
},
}))
defer server.Close()

// Request 1
resp, err := http.Get(server.URL)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
assert.Equal(t, `{"data":"Hello"}`, readBody(t, resp))

// Request 2
resp, err = http.Get(server.URL)
require.NoError(t, err)
assert.Equal(t, 400, resp.StatusCode)
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
assert.Equal(t, `{"error": "failed"}`, readBody(t, resp))

// Request 3
resp, err = http.Get(server.URL)
require.NoError(t, err)
assert.Equal(t, 503, resp.StatusCode)
assert.Equal(t, "", resp.Header.Get("Content-Type"))
assert.Equal(t, "", readBody(t, resp))
}

func readBody(t *testing.T, resp *http.Response) string {
Expand Down

0 comments on commit 07d4a35

Please sign in to comment.