Skip to content

Commit

Permalink
fix: support /livez & /readyz for ServerHTTP HandlerFunc as well (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
DrPsychick committed Apr 8, 2023
1 parent cb34fcf commit 42b4d66
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
8 changes: 8 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
l2 "log"
"net/http"
"strings"
"sync"
Expand All @@ -30,6 +31,13 @@ func (fn HandlerFunc) Serve(b *ResponseBuilder, r *RequestEnvelope) {

// ServeHTTP serves a HTTP request.
func (fn HandlerFunc) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if r.URL != nil && (strings.HasSuffix(r.URL.Path, "/livez") || strings.HasSuffix(r.URL.Path, "/readyz")) {
if _, err := rw.Write([]byte("ok")); err != nil {
l2.Fatal("error: could not write response")
}
return
}

req, err := parseRequest(r.Body)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
Expand Down
42 changes: 42 additions & 0 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,48 @@ func TestServer(t *testing.T) {
assert.NotEmpty(t, resp)
}

func TestServerHTTPProbes(t *testing.T) {
h := HandlerFunc(func(b *ResponseBuilder, r *RequestEnvelope) {})
rw := httptest.NewRecorder()
u, _ := url.Parse("http://anything.net/foobar/livez")
r := &http.Request{Method: http.MethodGet, URL: u}

h.ServeHTTP(rw, r)

res, err := io.ReadAll(rw.Result().Body)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, rw.Result().StatusCode)
assert.Contains(t, string(res), "ok")
}

func TestServerHTTP(t *testing.T) {
h := HandlerFunc(func(b *ResponseBuilder, r *RequestEnvelope) { b.WithSimpleCard("title", "TestServerHTTP") })
rw := httptest.NewRecorder()
b := io.NopCloser(bytes.NewReader([]byte(`{}`)))
r := &http.Request{Method: http.MethodGet, Body: b}

h.ServeHTTP(rw, r)

res, err := io.ReadAll(rw.Result().Body)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, rw.Result().StatusCode)
assert.Contains(t, string(res), "TestServerHTTP")
}

func TestServerHTTPFail(t *testing.T) {
h := HandlerFunc(func(b *ResponseBuilder, r *RequestEnvelope) {})
rw := httptest.NewRecorder()
b := io.NopCloser(bytes.NewReader([]byte(`invalid-json`)))
r := &http.Request{Method: http.MethodGet, Body: b}

h.ServeHTTP(rw, r)

res, err := io.ReadAll(rw.Result().Body)
assert.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, rw.Result().StatusCode)
assert.Contains(t, string(res), "failed to parse request")
}

func TestMuxServeHTTPProbes(t *testing.T) {
mux := NewServerMux(log.New(nil, log.ConsoleFormat(), log.Info))
rw := httptest.NewRecorder()
Expand Down

0 comments on commit 42b4d66

Please sign in to comment.