Skip to content

Commit

Permalink
adding healthz endpoint (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
dskatz authored Dec 15, 2021
1 parent b52f4b3 commit 97e4c7b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
18 changes: 18 additions & 0 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package server

import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
Expand Down Expand Up @@ -39,6 +41,7 @@ func New(opts ...ServerFuncOpt) (http.Handler, error) {
}
}

s.router.HandleFunc("/healthz", s.handleHealthz())
s.router.HandleFunc("/", s.handleRoot())

return s.router, nil
Expand Down Expand Up @@ -117,6 +120,21 @@ func (s *Server) handleRoot() http.HandlerFunc {
}
}

func (s *Server) handleHealthz() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
status := map[string]string{
"status": "ok",
}

bytes, err := json.Marshal(status)
if err != nil {
logAndError(w, http.StatusBadRequest, err, "error gathering status")
}
w.Header().Add("Content-Type", "application/json")
fmt.Fprint(w, string(bytes))
}
}

func logAndError(w http.ResponseWriter, code int, err error, msg string) {
log.WithError(err).Error(msg)
http.Error(w, http.StatusText(code), code)
Expand Down
22 changes: 22 additions & 0 deletions internal/server/server_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package server

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -155,3 +157,23 @@ func TestHandleRoot(t *testing.T) {
assert.Equal(t, "jhon", req.Header.Get("X-WEBAUTH-USER"))
assert.Equal(t, http.StatusOK, w.Code)
}

func TestHandleHealthz(t *testing.T) {
server, err := New()
assert.NoError(t, err)

w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/healthz", nil)
server.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
want := map[string]string{"status": "ok"}

buf := new(bytes.Buffer)
_, err = buf.ReadFrom(w.Result().Body)
assert.NoError(t, err)

got := map[string]string{}
err = json.Unmarshal(buf.Bytes(), &got)
assert.NoError(t, err)
assert.Equal(t, want, got)
}

0 comments on commit 97e4c7b

Please sign in to comment.