From 3453fc346ad4531e071bcae209aa8e36967a799f Mon Sep 17 00:00:00 2001 From: Jan Fuhrer Date: Wed, 8 May 2024 09:51:06 +0200 Subject: [PATCH] feat: add health endpoint --- pkg/http/health.go | 13 +++++++++++++ pkg/http/health_test.go | 33 +++++++++++++++++++++++++++++++++ pkg/http/server.go | 1 + 3 files changed, 47 insertions(+) create mode 100644 pkg/http/health.go create mode 100644 pkg/http/health_test.go diff --git a/pkg/http/health.go b/pkg/http/health.go new file mode 100644 index 0000000..26cb13e --- /dev/null +++ b/pkg/http/health.go @@ -0,0 +1,13 @@ +package http + +import ( + "net/http" +) + +func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + if _, err := w.Write([]byte(`{"status": "OK"}`)); err != nil { + http.Error(w, "Failed to write response", http.StatusInternalServerError) + } +} diff --git a/pkg/http/health_test.go b/pkg/http/health_test.go new file mode 100644 index 0000000..8c16005 --- /dev/null +++ b/pkg/http/health_test.go @@ -0,0 +1,33 @@ +//go:build unit + +package http + +import ( + "net/http" + "net/http/httptest" + "testing" + + "go.uber.org/zap/zaptest" +) + +func TestHealthHandler(t *testing.T) { + logger := zaptest.NewLogger(t) + config := &Config{ + Host: "localhost", + Port: "8080", + } + + server, _ := NewServer(config, logger) + server.registerHandlers() + + req := httptest.NewRequest("GET", "/health", nil) + req.Header.Set("User-Agent", "Mozilla/5.0") + w := httptest.NewRecorder() + server.router.ServeHTTP(w, req) + + resp := w.Result() + if resp.StatusCode != http.StatusOK { + t.Errorf("Expected status code %d, got %d", http.StatusOK, resp.StatusCode) + t.Errorf("Response body: %s", w.Body.String()) + } +} diff --git a/pkg/http/server.go b/pkg/http/server.go index c0a7f4a..eb942da 100644 --- a/pkg/http/server.go +++ b/pkg/http/server.go @@ -37,6 +37,7 @@ func NewServer(config *Config, logger *zap.Logger) (*Server, error) { func (s *Server) registerHandlers() { s.router.HandleFunc("/", s.indexHandler).HeadersRegexp("User-Agent", "^Mozilla.*").Methods("GET") + s.router.HandleFunc("/health", s.healthHandler).Methods("GET") } func (s *Server) registerMiddlewares() {