Skip to content

Commit 30329d1

Browse files
authored
Add health check endpoint and tests (#30)
* Add health check endpoint and tests * remove comment * add timeStamp in response
1 parent d0e93ef commit 30329d1

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

controllers/healthCheckHandler.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package controllers
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
"time"
7+
8+
"github.com/julienschmidt/httprouter"
9+
)
10+
11+
type HealthCheckResponse struct {
12+
Status string `json:"status"`
13+
Timestamp string `json:"timestamp"`
14+
}
15+
16+
func HealthCheckHandler(response http.ResponseWriter, request *http.Request, params httprouter.Params) {
17+
response.Header().Set("Content-Type", "application/json")
18+
19+
data := HealthCheckResponse{
20+
Status: "ok",
21+
Timestamp: time.Now().Format(time.RFC3339),
22+
}
23+
24+
if err := json.NewEncoder(response).Encode(data); err != nil {
25+
http.Error(response, `{"status":"error","message":"Internal Server Error"}`, http.StatusInternalServerError)
26+
return
27+
}
28+
}
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package controllers_test
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
"time"
9+
10+
"github.com/Real-Dev-Squad/discord-service/controllers"
11+
"github.com/stretchr/testify/assert"
12+
)
13+
14+
func TestHealthCheckHandler(t *testing.T) {
15+
req, err := http.NewRequest("GET", "/health", nil)
16+
assert.NoError(t, err)
17+
18+
rr := httptest.NewRecorder()
19+
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
20+
controllers.HealthCheckHandler(w, r, nil)
21+
})
22+
23+
handler.ServeHTTP(rr, req)
24+
25+
assert.Equal(t, http.StatusOK, rr.Code)
26+
assert.Equal(t, "application/json", rr.Header().Get("Content-Type"))
27+
28+
var response map[string]string
29+
err = json.Unmarshal(rr.Body.Bytes(), &response)
30+
assert.NoError(t, err)
31+
assert.Equal(t, "ok", response["status"])
32+
33+
// Validate the timestamp format
34+
timestamp, exists := response["timestamp"]
35+
assert.True(t, exists, "timestamp field should exist")
36+
_, err = time.Parse(time.RFC3339, timestamp)
37+
assert.NoError(t, err, "timestamp should be in RFC3339 format")
38+
}

routes/baseRoute.go

+1
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ import (
88

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

0 commit comments

Comments
 (0)