| iomodo | 90de915 | 2025-07-31 13:20:01 +0400 | [diff] [blame] | 1 | package api |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "log" |
| 6 | "net/http" |
| 7 | |
| 8 | "github.com/gin-gonic/gin" |
| 9 | "github.com/iomodo/staff/app" |
| 10 | ) |
| 11 | |
| 12 | const APIURLSuffix = "/api/v1" |
| 13 | const HealthCheckPath = "/healthcheck" |
| 14 | |
| 15 | type API struct { |
| iomodo | b23799d | 2025-07-31 14:08:22 +0400 | [diff] [blame] | 16 | Logger *log.Logger |
| 17 | Root *gin.Engine |
| 18 | APIRoot *gin.RouterGroup // 'api/v1' |
| 19 | Proposal *gin.RouterGroup // 'api/v1/proposal' |
| iomodo | 90de915 | 2025-07-31 13:20:01 +0400 | [diff] [blame] | 20 | } |
| 21 | |
| 22 | // Init initializes api |
| 23 | func 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() |
| iomodo | b23799d | 2025-07-31 14:08:22 +0400 | [diff] [blame] | 32 | apiObj.initProposal() |
| iomodo | 90de915 | 2025-07-31 13:20:01 +0400 | [diff] [blame] | 33 | |
| 34 | apiObj.Root.NoRoute(func(c *gin.Context) { |
| 35 | c.JSON(http.StatusNotFound, "Page not found") |
| 36 | }) |
| 37 | |
| 38 | return nil |
| 39 | } |
| 40 | |
| 41 | func (apiObj *API) initHealthCheck() { |
| 42 | apiObj.Root.GET(HealthCheckPath, healthCheck) |
| 43 | } |
| 44 | |
| 45 | func 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 | |
| 54 | func responseFormat(c *gin.Context, respStatus int, data interface{}) { |
| 55 | c.JSON(respStatus, data) |
| 56 | } |
| 57 | |
| 58 | func 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 | } |