From a9cb361e6b619e9e2632d00b8417521b1b917fba Mon Sep 17 00:00:00 2001 From: Jordan Hotmann Date: Wed, 24 Apr 2024 13:48:46 -0600 Subject: [PATCH] Recoverable API wrapper --- internal/api/api.go | 17 +++++++++++++++-- main.go | 2 +- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/internal/api/api.go b/internal/api/api.go index 67c3a28..fec0234 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -34,7 +34,20 @@ const ( HA_STATE_PREFIX = "homeassistant.states" ) -func Listen(parentLogger *slog.Logger, parentConfig *config.HatsConfig, readme []byte) { +func InitAPI(parentLogger *slog.Logger, parentConfig *config.HatsConfig, readme []byte) { + go func(parentLogger *slog.Logger, parentConfig *config.HatsConfig, readme []byte) { + for { + err := Listen(parentLogger, parentConfig, readme) + if err == nil { + break + } + parentLogger.Error("An error occurred with the API. Restarting now.", "error", err) + Close() + } + }(parentLogger, parentConfig, readme) +} + +func Listen(parentLogger *slog.Logger, parentConfig *config.HatsConfig, readme []byte) error { logger = parentLogger cfg = parentConfig @@ -82,7 +95,7 @@ func Listen(parentLogger *slog.Logger, parentConfig *config.HatsConfig, readme [ Handler: router, } - go server.ListenAndServe() + return server.ListenAndServe() } func Close() { diff --git a/main.go b/main.go index 60ed118..66f0dca 100644 --- a/main.go +++ b/main.go @@ -66,7 +66,7 @@ func main() { ntfy.InitClient(cfg) - api.Listen(logger, cfg, readme) + api.InitAPI(logger, cfg, readme) defer api.Close() for sig := range interrupt {