diff --git a/main.go b/main.go index eea5a4e..9d9523f 100644 --- a/main.go +++ b/main.go @@ -164,9 +164,13 @@ func main() { // Handlers heartbeatHandler := &routes.HeartbeatHandler{HeartbeatSrvc: heartbeatSrvc} summaryHandler := &routes.SummaryHandler{SummarySrvc: summarySrvc} + healthHandler := &routes.HealthHandler{Db: db} // Middlewares - authenticateMiddleware := &middlewares.AuthenticateMiddleware{UserSrvc: userSrvc} + authenticateMiddleware := &middlewares.AuthenticateMiddleware{ + UserSrvc: userSrvc, + WhitelistPaths: []string{"/api/health"}, + } basicAuthMiddleware := &middlewares.RequireBasicAuthMiddleware{} corsMiddleware := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, @@ -185,6 +189,7 @@ func main() { // API Routes apiRouter.Path("/heartbeat").Methods(http.MethodPost).HandlerFunc(heartbeatHandler.ApiPost) apiRouter.Path("/summary").Methods(http.MethodGet).HandlerFunc(summaryHandler.ApiGet) + apiRouter.Path("/health").Methods(http.MethodGet).HandlerFunc(healthHandler.ApiGet) // Static Routes router.PathPrefix("/assets").Handler(negroni.Classic().With(negroni.Wrap(http.FileServer(http.Dir("./static"))))) diff --git a/middlewares/authenticate.go b/middlewares/authenticate.go index e5926c4..3b0dc57 100644 --- a/middlewares/authenticate.go +++ b/middlewares/authenticate.go @@ -18,9 +18,10 @@ import ( ) type AuthenticateMiddleware struct { - UserSrvc *services.UserService - Cache *cache.Cache - Initialized bool + UserSrvc *services.UserService + Cache *cache.Cache + WhitelistPaths []string + Initialized bool } func (m *AuthenticateMiddleware) Init() { @@ -35,6 +36,13 @@ func (m *AuthenticateMiddleware) Handle(w http.ResponseWriter, r *http.Request, m.Init() } + for _, p := range m.WhitelistPaths { + if strings.HasPrefix(r.URL.Path, p) || r.URL.Path == p { + next(w, r) + return + } + } + var user *models.User var userKey string user, userKey, err := m.tryGetUserByPassword(r) diff --git a/routes/health.go b/routes/health.go new file mode 100644 index 0000000..c822e01 --- /dev/null +++ b/routes/health.go @@ -0,0 +1,21 @@ +package routes + +import ( + "fmt" + "github.com/jinzhu/gorm" + "net/http" +) + +type HealthHandler struct { + Db *gorm.DB +} + +func (h *HealthHandler) ApiGet(w http.ResponseWriter, r *http.Request) { + var dbStatus int + if err := h.Db.DB().Ping(); err == nil { + dbStatus = 1 + } + + w.Header().Set("Content-Type", "text/plain") + w.Write([]byte(fmt.Sprintf("app=1\ndb=%d", dbStatus))) +}