Skip to content

Commit

Permalink
add graceful shutdown (#88)
Browse files Browse the repository at this point in the history
Signed-off-by: Akash Kumar <[email protected]>
  • Loading branch information
AkashKumar7902 authored Dec 28, 2023
1 parent e586970 commit ffc250c
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions gin-mongo/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package main

import (
"context"
"net/http"
"os"
"time"

"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/mongo"

"os/signal"
"syscall"

"go.uber.org/zap"
)

Expand Down Expand Up @@ -34,6 +40,27 @@ func main() {

r.GET("/:param", getURL)
r.POST("/url", putURL)
srv := &http.Server{
Addr: ":" + port,
Handler: r,
}

r.Run(":" + port)
}
stopper := make(chan os.Signal, 1)
signal.Notify(stopper, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
select {
case <-stopper:
ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
logger.Fatal("Server Shutdown:", zap.Error(err))
}
logger.Info("stopper called")
}
}()

if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Fatal("listen: %s\n", zap.Error(err))
}
logger.Info("server exiting")
}

0 comments on commit ffc250c

Please sign in to comment.