Make the signal handler work properly

This commit is contained in:
Bendodroid 2023-11-10 03:49:05 +01:00
commit baf73f33e7
Signed by: bendodroid
GPG key ID: 3EEE19A0F73D5FFC
2 changed files with 19 additions and 16 deletions

22
main.go
View file

@ -8,6 +8,7 @@ import (
"syscall"
"gitlab.hamburg.ccc.de/ccchh/spaceapid/handlers"
"gitlab.hamburg.ccc.de/ccchh/spaceapid/types"
"gitlab.hamburg.ccc.de/ccchh/spaceapid/util"
)
@ -21,20 +22,21 @@ func main() {
// Merge old state if present
util.MergeOldState(&spaceApiResponse)
// Register signal handler
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM)
go func(ch chan os.Signal, resp *types.SpaceAPIResponseV14) {
<-ch
log.Println("Saving state and shutting down...")
util.SaveCurrentState(*resp)
os.Exit(0)
}(sc, &spaceApiResponse)
// Register HTTP handlers
http.HandleFunc("/", handlers.Root(&spaceApiResponse))
http.HandleFunc("/state/open", handlers.StateOpen(config.BAUsername, config.BAPassword, &spaceApiResponse))
// Start webserver
log.Println("Starting HTTP server...")
go log.Fatalln(http.ListenAndServe(":8080", nil))
// Wait for exit signal
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM)
<-sc
// Save state for next run
log.Println("Saving state and shutting down...")
util.SaveCurrentState(spaceApiResponse)
log.Fatalln(http.ListenAndServe(":8080", nil))
}