Skip to content

Commit

Permalink
chore(gin): add graceful shutdown
Browse files Browse the repository at this point in the history
Signed-off-by: Bo-Yi.Wu <[email protected]>
  • Loading branch information
appleboy committed Aug 20, 2022
1 parent c81c1c3 commit 39e6427
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions cmd/server/gin/main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package main

import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -38,7 +42,18 @@ func main() {
MaxHeaderBytes: 8 * 1024, // 8KiB
}

if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("HTTP listen and serve: %v", err)
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("HTTP listen and serve: %v", err)
}
}()

<-signals
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("HTTP shutdown: %v", err) // nolint:gocritic
}
}

0 comments on commit 39e6427

Please sign in to comment.