| 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' |
| Proposal *gin.RouterGroup // 'api/v1/proposal' |
| } |
| |
| // 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.initProposal() |
| |
| 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 |
| } |