Skip to content

Commit

Permalink
Use signal.NotifyContext for idiomatic, graceful shutdown (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasrod16 authored Oct 11, 2024
2 parents af1d975 + 86629f7 commit 177fabf
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ func main() {
log.Fatalf("failed to load UI assets: %v", err)
}

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

c := cache.New()

Expand All @@ -36,7 +36,8 @@ func main() {
for {
select {
case <-ctx.Done():
log.Fatal(ctx.Err())
log.Println(ctx.Err())
return
case <-ticker.C:
if err := c.RepoData(ctx); err != nil {
log.Printf("Error fetching GitHub repo data: %v", err)
Expand Down Expand Up @@ -64,19 +65,21 @@ func main() {
WriteTimeout: 5 * time.Second,
}

shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)

go func() {
log.Println("API server listening on port 8080")
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}()

<-shutdown
<-ctx.Done()
stop()
log.Println("Shutting down server...")
if err := server.Shutdown(ctx); err != nil {

shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

if err := server.Shutdown(shutdownCtx); err != nil {
log.Fatal(err)
}
log.Println("Server gracefully shutdown")
Expand Down

0 comments on commit 177fabf

Please sign in to comment.