Skip to content
This repository has been archived by the owner on Sep 12, 2024. It is now read-only.

Commit

Permalink
api: add a basic health checking endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
nettoclaudio committed Jul 26, 2018
1 parent b705c47 commit af15239
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
17 changes: 17 additions & 0 deletions api/health.go
Original file line number Diff line number Diff line change
@@ -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")
}
57 changes: 57 additions & 0 deletions api/health_test.go
Original file line number Diff line number Diff line change
@@ -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())
})
}
2 changes: 2 additions & 0 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit af15239

Please sign in to comment.