blob: ae0af3661cb65d5e5954c2a9938aaf658a71ab81 [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 {
iomodob23799d2025-07-31 14:08:22 +040016 Logger *log.Logger
17 Root *gin.Engine
18 APIRoot *gin.RouterGroup // 'api/v1'
19 Proposal *gin.RouterGroup // 'api/v1/proposal'
iomodo90de9152025-07-31 13:20:01 +040020}
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()
iomodob23799d2025-07-31 14:08:22 +040032 apiObj.initProposal()
iomodo90de9152025-07-31 13:20:01 +040033
34 apiObj.Root.NoRoute(func(c *gin.Context) {
35 c.JSON(http.StatusNotFound, "Page not found")
36 })
37
38 return nil
39}
40
41func (apiObj *API) initHealthCheck() {
42 apiObj.Root.GET(HealthCheckPath, healthCheck)
43}
44
45func healthCheck(c *gin.Context) {
46 _, err := getApp(c)
47 if err != nil {
48 responseFormat(c, http.StatusInternalServerError, err.Error())
49 return
50 }
51 responseFormat(c, http.StatusOK, "OK")
52}
53
54func responseFormat(c *gin.Context, respStatus int, data interface{}) {
55 c.JSON(respStatus, data)
56}
57
58func getApp(c *gin.Context) (*app.App, error) {
59 appInt, ok := c.Get("app")
60 if !ok {
61 return nil, fmt.Errorf("missing application in the context")
62 }
63 a, ok := appInt.(*app.App)
64 if !ok {
65 return nil, fmt.Errorf("wrong data type of the application in the context")
66 }
67 return a, nil
68}