1. package main
    2. import (
    3. "context"
    4. "log"
    5. "net/http"
    6. "os"
    7. "os/signal"
    8. "syscall"
    9. "time"
    10. "github.com/gin-gonic/gin"
    11. )
    12. func main() {
    13. router := gin.Default()
    14. router.GET("/", func(c *gin.Context) {
    15. time.Sleep(5 * time.Second)
    16. c.String(http.StatusOK, "Welcome Gin Server")
    17. })
    18. srv := &http.Server{
    19. Addr: ":8080",
    20. Handler: router,
    21. }
    22. go func() {
    23. // service connections
    24. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
    25. log.Fatalf("listen: %s\n", err)
    26. }
    27. }()
    28. // Wait for interrupt signal to gracefully shutdown the server with
    29. // a timeout of 5 seconds.
    30. quit := make(chan os.Signal)
    31. // kill (no param) default send syscanll.SIGTERM
    32. // kill -2 is syscall.SIGINT
    33. // kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
    34. signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    35. <-quit
    36. log.Println("Shutdown Server ...")
    37. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    38. defer cancel()
    39. if err := srv.Shutdown(ctx); err != nil {
    40. log.Fatal("Server Shutdown:", err)
    41. }
    42. // catching ctx.Done(). timeout of 5 seconds.
    43. select {
    44. case <-ctx.Done():
    45. log.Println("timeout of 5 seconds.")
    46. }
    47. log.Println("Server exiting")
    48. }