Skip to content

Commit

Permalink
Merge pull request #59 from caas-team/feat/globalTargetHandler
Browse files Browse the repository at this point in the history
feat: add simple okHandler for api
  • Loading branch information
y-eight authored Jan 5, 2024
2 parents 3a13eb0 + 4f7d12b commit ab56ca0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
18 changes: 18 additions & 0 deletions pkg/sparrow/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ func (s *Sparrow) register(ctx context.Context) {
// handlers are (de)registered by the checks themselves
s.router.HandleFunc("/checks/*", s.handleChecks)

// Handles requests with simple http ok
// Required for global targets in checks
s.router.Handle("/", okHandler(ctx))

// Handles prometheus metrics
s.router.Handle("/metrics",
promhttp.HandlerFor(
s.metrics.GetRegistry(),
Expand Down Expand Up @@ -110,6 +115,19 @@ func (s *Sparrow) api(ctx context.Context) error {
return nil
}

// okHandler returns a handler that will serve status ok
func okHandler(ctx context.Context) http.Handler {
log := logger.FromContext(ctx)

return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("ok"))
if err != nil {
log.Error("Could not write response", "error", err.Error())
}
})
}

var oapiBoilerplate = openapi3.T{
// this object should probably be user defined
OpenAPI: "3.0.0",
Expand Down
27 changes: 26 additions & 1 deletion pkg/sparrow/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func TestSparrow_register(t *testing.T) {

s.register(context.Background())

expectedRoutes := []string{"/openapi.yaml", "/v1/metrics/{checkName}", "/checks/*", "/metrics"}
expectedRoutes := []string{"/openapi.yaml", "/v1/metrics/{checkName}", "/checks/*", "/metrics", "/"}
routes := r.Routes()
for _, route := range expectedRoutes {
found := 0
Expand Down Expand Up @@ -291,3 +291,28 @@ func TestSparrow_getOpenapi(t *testing.T) {
})
}
}

func Test_okHandler(t *testing.T) {
ctx := context.Background()

req, err := http.NewRequestWithContext(ctx, "GET", "/okHandler", http.NoBody)
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()
handler := okHandler(ctx)

handler.ServeHTTP(rr, req)

if status := rr.Code; status != http.StatusOK {
t.Errorf("Handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}

expected := "ok"
if rr.Body.String() != expected {
t.Errorf("Handler returned unexpected body: got %v want %v",
rr.Body.String(), expected)
}
}

0 comments on commit ab56ca0

Please sign in to comment.