Skip to content

Commit

Permalink
feat: add health endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
janfuhrer committed May 8, 2024
1 parent e01fe0c commit 3453fc3
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pkg/http/health.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
33 changes: 33 additions & 0 deletions pkg/http/health_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
}
1 change: 1 addition & 0 deletions pkg/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down

0 comments on commit 3453fc3

Please sign in to comment.