Skip to content

Commit

Permalink
Improve health check endpoint to test database connection
Browse files Browse the repository at this point in the history
  • Loading branch information
fguillot committed Feb 20, 2021
1 parent c2571f9 commit e3c28a6
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 14 deletions.
10 changes: 7 additions & 3 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,17 +126,21 @@ func Parse() {
config.Opts.DatabaseMaxConns(),
)
if err != nil {
logger.Fatal("Unable to connect to the database: %v", err)
logger.Fatal("Unable to initialize database connection pool: %v", err)
}
defer db.Close()

store := storage.NewStorage(db)

if err := store.Ping(); err != nil {
logger.Fatal("Unable to connect to the database: %v", err)
}

if flagMigrate {
database.Migrate(db)
return
}

store := storage.NewStorage(db)

if flagResetFeedErrors {
store.ResetFeedErrors()
return
Expand Down
5 changes: 5 additions & 0 deletions service/httpd/httpd.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,11 @@ func setupHandler(store *storage.Storage, pool *worker.Pool) *mux.Router {
ui.Serve(router, store, pool)

router.HandleFunc("/healthcheck", func(w http.ResponseWriter, r *http.Request) {
if err := store.Ping(); err != nil {
http.Error(w, "Database Connection Error", http.StatusInternalServerError)
return
}

w.Write([]byte("OK"))
}).Name("healthcheck")

Expand Down
11 changes: 0 additions & 11 deletions storage/feed.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,6 @@ func (s *Storage) CountFeeds(userID int64) int {
return result
}

// DatabaseVersion returns the version of the database which is in use
func (s *Storage) DatabaseVersion() string {
var dbVersion string
err := s.db.QueryRow(`SELECT current_setting('server_version')`).Scan(&dbVersion)
if err != nil {
return err.Error()
}

return dbVersion
}

// CountUserFeedsWithErrors returns the number of feeds with parsing errors that belong to the given user.
func (s *Storage) CountUserFeedsWithErrors(userID int64) int {
pollingParsingErrorLimit := config.Opts.PollingParsingErrorLimit()
Expand Down
17 changes: 17 additions & 0 deletions storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,20 @@ type Storage struct {
func NewStorage(db *sql.DB) *Storage {
return &Storage{db}
}

// DatabaseVersion returns the version of the database which is in use.
func (s *Storage) DatabaseVersion() string {
var dbVersion string
err := s.db.QueryRow(`SELECT current_setting('server_version')`).Scan(&dbVersion)
if err != nil {
return err.Error()
}

return dbVersion
}

// Ping checks if the database connection works.
func (s *Storage) Ping() error {
_, err := s.db.Exec(`SELECT true`)
return err
}

0 comments on commit e3c28a6

Please sign in to comment.