Skip to content

Commit

Permalink
feat: test json response on health endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
logan-bobo committed May 26, 2024
1 parent fc02a17 commit af0b7d6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
8 changes: 5 additions & 3 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import "net/http"

type apiConfig struct{}

type HealthResponse struct {
Status string `json:"status"`
}

func (apiCfg *apiConfig) healthz(w http.ResponseWriter, r *http.Request) {
payload := struct {
Status string `json:"status"`
}{
payload := HealthResponse {
Status: "ok",
}

Expand Down
17 changes: 13 additions & 4 deletions handlers_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
Expand All @@ -15,11 +16,19 @@ func TestHealthEndpoint(t *testing.T){

apiCfg.healthz(response, request)

got := response.Body.String()
want := `{"status":"ok"}`
got := HealthResponse{}
err := json.NewDecoder(response.Body).Decode(&got)

if got != want {
t.Errorf("got %q wanted %q", got, want)
if err != nil {
t.Errorf("unable to parse response %q into %q", response.Body, got)
}

if got.Status != "ok" {
t.Errorf("status field must be okay on health response got %q wanted %q", got.Status, "ok")
}

if response.Result().StatusCode != http.StatusOK {
t.Error("endpoint must return 200")
}
})
}

0 comments on commit af0b7d6

Please sign in to comment.