Skip to content

Commit

Permalink
Make sure all goroutines shut down before exit
Browse files Browse the repository at this point in the history
Wait for the stopChannel to respond and to close before exiting
  • Loading branch information
Ajnasz committed Oct 16, 2021
1 parent a52c5fb commit 014b7da
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ func scheduleDeleteExpired(entryStorage storage.VerifyStorage, stopChan chan int
case <-time.After(time.Second):
entryStorage.DeleteExpired()
case <-stopChan:
stopChan <- struct{}{}
close(stopChan)
return
}
}
Expand Down Expand Up @@ -181,7 +183,7 @@ func main() {
<-termChan
ctx := context.Background()
// on close
c := shutDown(func() error {
shutdownErrors := shutDown(func() error {
ctx, cancel := context.WithTimeout(ctx, time.Second*5)
defer cancel()
return httpServer.Shutdown(ctx)
Expand All @@ -192,12 +194,31 @@ func main() {
return nil
})

for err := range c {
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s", err)
os.Exit(1)
errored := false
for {
select {
case err, ok := <-shutdownErrors:
if err != nil {
errored = true
fmt.Fprintf(os.Stderr, "error: %s", err)
}
if !ok {
shutdownErrors = nil
}
case _, ok := <-stopChan:
if !ok {
stopChan = nil
}
case <-time.After(time.Second * 15):
fmt.Println("error: force quit")
os.Exit(2)
}
}

os.Exit(0)
if shutdownErrors == nil && stopChan == nil {
if errored {
os.Exit(1)
}
return
}
}
}

0 comments on commit 014b7da

Please sign in to comment.