blob: fd78ee40820c76d524279d813a226d7345d48f2d [file] [log] [blame]
iomodo90de9152025-07-31 13:20:01 +04001package api
2
3import (
4 "fmt"
5 "log"
6 "net/http"
7
8 "github.com/gin-gonic/gin"
9 "github.com/iomodo/staff/app"
10)
11
12const APIURLSuffix = "/api/v1"
13const HealthCheckPath = "/healthcheck"
14
15type API struct {
16 Logger *log.Logger
17 Root *gin.Engine
18 APIRoot *gin.RouterGroup // 'api/v1'
19 Auth *gin.RouterGroup // 'api/v1/auth'
20}
21
22// Init initializes api
23func Init(router *gin.Engine, application *app.App) error {
24 apiObj := API{}
25 apiObj.Root = router
26 apiObj.Root.Use(func(c *gin.Context) {
27 c.Set("app", application)
28 c.Next()
29 })
30 apiObj.APIRoot = router.Group(APIURLSuffix)
31 apiObj.initHealthCheck()
32
33 apiObj.Root.NoRoute(func(c *gin.Context) {
34 c.JSON(http.StatusNotFound, "Page not found")
35 })
36
37 return nil
38}
39
40func (apiObj *API) initHealthCheck() {
41 apiObj.Root.GET(HealthCheckPath, healthCheck)
42}
43
44func healthCheck(c *gin.Context) {
45 _, err := getApp(c)
46 if err != nil {
47 responseFormat(c, http.StatusInternalServerError, err.Error())
48 return
49 }
50 responseFormat(c, http.StatusOK, "OK")
51}
52
53func responseFormat(c *gin.Context, respStatus int, data interface{}) {
54 c.JSON(respStatus, data)
55}
56
57func getApp(c *gin.Context) (*app.App, error) {
58 appInt, ok := c.Get("app")
59 if !ok {
60 return nil, fmt.Errorf("missing application in the context")
61 }
62 a, ok := appInt.(*app.App)
63 if !ok {
64 return nil, fmt.Errorf("wrong data type of the application in the context")
65 }
66 return a, nil
67}