http.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package http
  2. import (
  3. "context"
  4. "github.com/gin-gonic/gin"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/signal"
  9. "syscall"
  10. "time"
  11. )
  12. func Run(r *gin.Engine, addr string) {
  13. srv := &http.Server{
  14. Addr: addr,
  15. Handler: r,
  16. }
  17. // Initializing the server in a goroutine so that
  18. // it won't block the graceful shutdown handling below
  19. go func() {
  20. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  21. log.Fatalf("listen: %s\n", err)
  22. }
  23. }()
  24. // Wait for interrupt signal to gracefully shutdown the server with
  25. // a timeout of 5 seconds.
  26. quit := make(chan os.Signal, 1)
  27. // kill (no param) default send syscall.SIGTERM
  28. // kill -2 is syscall.SIGINT
  29. // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
  30. signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  31. <-quit
  32. log.Println("Shutting down server...")
  33. // The context is used to inform the server it has 5 seconds to finish
  34. // the request it is currently handling
  35. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  36. defer cancel()
  37. if err := srv.Shutdown(ctx); err != nil {
  38. log.Fatal("Server forced to shutdown: ", err)
  39. }
  40. log.Println("Server exiting")
  41. }