Skip to content

Commit

Permalink
Add health check endpoint and tests (#30)
Browse files Browse the repository at this point in the history
* Add health check endpoint and tests

* remove comment

* add timeStamp in response
  • Loading branch information
Devashish08 authored Dec 3, 2024
1 parent d0e93ef commit 30329d1
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
28 changes: 28 additions & 0 deletions controllers/healthCheckHandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package controllers

import (
"encoding/json"
"net/http"
"time"

"github.com/julienschmidt/httprouter"
)

type HealthCheckResponse struct {
Status string `json:"status"`
Timestamp string `json:"timestamp"`
}

func HealthCheckHandler(response http.ResponseWriter, request *http.Request, params httprouter.Params) {
response.Header().Set("Content-Type", "application/json")

data := HealthCheckResponse{
Status: "ok",
Timestamp: time.Now().Format(time.RFC3339),
}

if err := json.NewEncoder(response).Encode(data); err != nil {
http.Error(response, `{"status":"error","message":"Internal Server Error"}`, http.StatusInternalServerError)
return
}
}
38 changes: 38 additions & 0 deletions controllers/healthCheckHandler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package controllers_test

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/Real-Dev-Squad/discord-service/controllers"
"github.com/stretchr/testify/assert"
)

func TestHealthCheckHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/health", nil)
assert.NoError(t, err)

rr := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
controllers.HealthCheckHandler(w, r, nil)
})

handler.ServeHTTP(rr, req)

assert.Equal(t, http.StatusOK, rr.Code)
assert.Equal(t, "application/json", rr.Header().Get("Content-Type"))

var response map[string]string
err = json.Unmarshal(rr.Body.Bytes(), &response)
assert.NoError(t, err)
assert.Equal(t, "ok", response["status"])

// Validate the timestamp format
timestamp, exists := response["timestamp"]
assert.True(t, exists, "timestamp field should exist")
_, err = time.Parse(time.RFC3339, timestamp)
assert.NoError(t, err, "timestamp should be in RFC3339 format")
}
1 change: 1 addition & 0 deletions routes/baseRoute.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ import (

func SetupBaseRoutes(router *httprouter.Router) {
router.POST("/", middleware.VerifyCommand(controllers.HomeHandler))
router.GET("/health", controllers.HealthCheckHandler)
}

0 comments on commit 30329d1

Please sign in to comment.