From 058c616667aa4aa0506a7fd206c892c686e24f0f Mon Sep 17 00:00:00 2001 From: Yasen Pramatarov Date: Wed, 16 Oct 2024 09:45:07 +0300 Subject: [PATCH] Adds a health check --- jilo-server.conf | 5 +++++ main.go | 34 +++++++++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/jilo-server.conf b/jilo-server.conf index 1bce772..1341c24 100644 --- a/jilo-server.conf +++ b/jilo-server.conf @@ -1,2 +1,7 @@ # database location database_path: "./jilo-server.db" + +# health check +health_check_enabled: true +health_check_port: 8080 +health_check_endpoint: "/health" diff --git a/main.go b/main.go index d685393..346494c 100644 --- a/main.go +++ b/main.go @@ -18,17 +18,23 @@ import ( // Structures type Agent struct { - ID int - URL string - Secret string - CheckPeriod int + ID int + URL string + Secret string + CheckPeriod int } type Config struct { - DatabasePath string `yaml:"database_path"` + DatabasePath string `yaml:"database_path"` + HealthCheckEnabled bool `yaml:"health_check_enabled"` + HealthCheckPort int `yaml:"health_check_port"` + HealthCheckEndpoint string `yaml:"health_check_endpoint"` } var defaultConfig = Config { DatabasePath: "./jilo-server.db", + HealthCheckEnabled: false, + HealthCheckPort: 8080, + HealthCheckEndpoint: "/health", } // Loading the config file @@ -50,6 +56,19 @@ func readConfig(filePath string) Config { return config } +// Start the health check +func startHealthCheckServer(port int, endpoint string) { + http.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte("Jilo Server is running")) + }) + + address := fmt.Sprintf(":%d", port) + + log.Printf("Starting health check server on %s%s", address, endpoint) + go http.ListenAndServe(address, nil) +} + // Database initialization func setupDatabase(dbPath string, initDB bool) (*sql.DB, error) { @@ -259,6 +278,11 @@ func main() { log.Printf("Using config file %s", finalConfigPath) config := readConfig(finalConfigPath) + // Start the health check, if it's enabled in the config file + if config.HealthCheckEnabled { + startHealthCheckServer(config.HealthCheckPort, config.HealthCheckEndpoint) + } + // Connect to or setup the database log.Println("Initializing the database...") db, err := setupDatabase(config.DatabasePath, *initDB)