diff --git a/api/health.go b/api/health.go new file mode 100644 index 0000000..76324ed --- /dev/null +++ b/api/health.go @@ -0,0 +1,17 @@ +package api + +import ( + "net/http" + + "github.com/labstack/echo" + "github.com/tsuru/cst/db" +) + +func health(ctx echo.Context) error { + + if db.GetStorage().Ping() { + return ctx.String(http.StatusOK, "WORKING") + } + + return ctx.String(http.StatusInternalServerError, "DOWN") +} diff --git a/api/health_test.go b/api/health_test.go new file mode 100644 index 0000000..dc892d3 --- /dev/null +++ b/api/health_test.go @@ -0,0 +1,57 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/tsuru/cst/db" + + "github.com/labstack/echo" + "github.com/stretchr/testify/require" +) + +func TestHealth(t *testing.T) { + + t.Run(`When system is unhealthy, should return 500 error`, func(t *testing.T) { + + db.SetStorage(&db.MockStorage{}) + + e := echo.New() + + request := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(``)) + + recorder := httptest.NewRecorder() + context := e.NewContext(request, recorder) + + health(context) + + require.Equal(t, http.StatusInternalServerError, recorder.Code) + assert.Equal(t, "DOWN", recorder.Body.String()) + }) + + t.Run(`When system is working, should return 200 code`, func(t *testing.T) { + + storage := &db.MockStorage{ + MockPing: func() bool { + return true + }, + } + + db.SetStorage(storage) + + e := echo.New() + + request := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(``)) + + recorder := httptest.NewRecorder() + context := e.NewContext(request, recorder) + + health(context) + + require.Equal(t, http.StatusOK, recorder.Code) + assert.Equal(t, "WORKING", recorder.Body.String()) + }) +} diff --git a/api/server.go b/api/server.go index 109da0a..3ba1bb0 100644 --- a/api/server.go +++ b/api/server.go @@ -36,6 +36,8 @@ func (ws *SecureWebServer) Start() error { ws.echo.Use(middleware.Recover()) ws.echo.Use(middleware.Logger()) + ws.echo.GET("/health", health) + v1 := ws.echo.Group("/v1") v1.POST("/scan", createScan) v1.GET("/scan/:image", showScans)