Add api package
Change-Id: Ifcdd1f45c01e98b91c1edef3371332cb4a098e82
diff --git a/server/api/api.go b/server/api/api.go
new file mode 100644
index 0000000..fd78ee4
--- /dev/null
+++ b/server/api/api.go
@@ -0,0 +1,67 @@
+package api
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/iomodo/staff/app"
+)
+
+const APIURLSuffix = "/api/v1"
+const HealthCheckPath = "/healthcheck"
+
+type API struct {
+ Logger *log.Logger
+ Root *gin.Engine
+ APIRoot *gin.RouterGroup // 'api/v1'
+ Auth *gin.RouterGroup // 'api/v1/auth'
+}
+
+// Init initializes api
+func Init(router *gin.Engine, application *app.App) error {
+ apiObj := API{}
+ apiObj.Root = router
+ apiObj.Root.Use(func(c *gin.Context) {
+ c.Set("app", application)
+ c.Next()
+ })
+ apiObj.APIRoot = router.Group(APIURLSuffix)
+ apiObj.initHealthCheck()
+
+ apiObj.Root.NoRoute(func(c *gin.Context) {
+ c.JSON(http.StatusNotFound, "Page not found")
+ })
+
+ return nil
+}
+
+func (apiObj *API) initHealthCheck() {
+ apiObj.Root.GET(HealthCheckPath, healthCheck)
+}
+
+func healthCheck(c *gin.Context) {
+ _, err := getApp(c)
+ if err != nil {
+ responseFormat(c, http.StatusInternalServerError, err.Error())
+ return
+ }
+ responseFormat(c, http.StatusOK, "OK")
+}
+
+func responseFormat(c *gin.Context, respStatus int, data interface{}) {
+ c.JSON(respStatus, data)
+}
+
+func getApp(c *gin.Context) (*app.App, error) {
+ appInt, ok := c.Get("app")
+ if !ok {
+ return nil, fmt.Errorf("missing application in the context")
+ }
+ a, ok := appInt.(*app.App)
+ if !ok {
+ return nil, fmt.Errorf("wrong data type of the application in the context")
+ }
+ return a, nil
+}