From 5c899a4cf093142c989d5a9ed2760f73b9ab746d Mon Sep 17 00:00:00 2001 From: Marvin Wendt Date: Sun, 11 Dec 2022 16:27:46 +0100 Subject: [PATCH] [#1233] added health API endpoint --- apis/base.go | 1 + apis/health.go | 28 ++++++++++++++++++++++++++++ apis/health_test.go | 25 +++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 apis/health.go create mode 100644 apis/health_test.go diff --git a/apis/base.go b/apis/base.go index 5aee0914..4ae4620a 100644 --- a/apis/base.go +++ b/apis/base.go @@ -100,6 +100,7 @@ func InitApi(app core.App) (*echo.Echo, error) { bindFileApi(app, api) bindRealtimeApi(app, api) bindLogsApi(app, api) + bindHealthApi(app, api) // health check should always be initialized after everything else is done // trigger the custom BeforeServe hook for the created api router // allowing users to further adjust its options or register new routes diff --git a/apis/health.go b/apis/health.go new file mode 100644 index 00000000..9a1520f7 --- /dev/null +++ b/apis/health.go @@ -0,0 +1,28 @@ +package apis + +import ( + "github.com/labstack/echo/v5" + "github.com/pocketbase/pocketbase/core" + "net/http" +) + +// bindHealthApi registers the health api endpoint. +func bindHealthApi(app core.App, rg *echo.Group) { + api := healthApi{app: app} + + subGroup := rg.Group("/health") + subGroup.GET("", api.healthCheck) +} + +type healthApi struct { + app core.App +} + +// healthCheck returns a 200 OK response if the server is healthy. +func (api *healthApi) healthCheck(c echo.Context) error { + payload := map[string]any{ + "code": http.StatusOK, + "message": "API is healthy.", + } + return c.JSON(http.StatusOK, payload) +} diff --git a/apis/health_test.go b/apis/health_test.go new file mode 100644 index 00000000..8633b0e0 --- /dev/null +++ b/apis/health_test.go @@ -0,0 +1,25 @@ +package apis_test + +import ( + "github.com/pocketbase/pocketbase/tests" + "net/http" + "testing" +) + +func TestHealthAPI(t *testing.T) { + scenarios := []tests.ApiScenario{ + { + Name: "health status returns 200", + Method: http.MethodGet, + Url: "/api/health", + ExpectedStatus: 200, + ExpectedContent: []string{ + `"code":200`, + }, + }, + } + + for _, scenario := range scenarios { + scenario.Test(t) + } +}