Adds a health check

main
Yasen Pramatarov 2024-10-16 09:45:07 +03:00
parent a648072ab4
commit 058c616667
2 changed files with 34 additions and 5 deletions

View File

@ -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"

24
main.go
View File

@ -25,10 +25,16 @@ type Agent struct {
}
type Config struct {
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)