• Gin框架系列之优雅重启或关闭


    在gin中通过如下代码可以正常的启动一个服务:

    package main
    
    import (
        "github.com/gin-gonic/gin"
        "net/http"
    )
    
    func main() {
        router := gin.Default()
    
        router.GET("/index", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{
                "message": "main site",
            })
        })
    
        router.Run(":8000")
    }

    但是如何让服务停止呢?比如 ctrl+c强制性关闭总是不太优雅,可以手动方式来实现:

    package main
    
    import (
        "context"
        "errors"
        "github.com/gin-gonic/gin"
        "log"
        "net/http"
        "os"
        "os/signal"
        "syscall"
        "time"
    )
    
    func main() {
        router := gin.Default()
        router.GET("/", func(c *gin.Context) {
            time.Sleep(5 * time.Second)
            c.String(http.StatusOK, "Welcome Gin Server")
        })
    
        srv := &http.Server{
            Addr:    ":8080",
            Handler: router,
        }
    
        // Initializing the server in a goroutine so that
        // it won't block the graceful shutdown handling below
        go func() {
            if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
                log.Printf("listen: %s\n", err)
            }
        }()
    
        // Wait for interrupt signal to gracefully shutdown the server with
        // a timeout of 5 seconds.
        quit := make(chan os.Signal)
        // kill (no param) default send syscall.SIGTERM
        // kill -2 is syscall.SIGINT
        // kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it
        signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
        <-quit
        log.Println("Shutting down server...")
    
        // The context is used to inform the server it has 5 seconds to finish
        // the request it is currently handling
        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
    
        if err := srv.Shutdown(ctx); err != nil {
            log.Fatal("Server forced to shutdown:", err)
        }
    
        log.Println("Server exiting")
    }
  • 相关阅读:
    HTML5结构
    HTML5新增的非主体元素header元素、footer元素、hgroup元素、adress元素
    CF GYM 100703G Game of numbers
    CF GYM 100703I Endeavor for perfection
    CF GYM 100703K Word order
    CF GYM 100703L Many questions
    CF GYM 100703M It's complicate
    HDU 5313 Bipartite Graph
    CF 560e Gerald and Giant Chess
    POJ 2479 Maximum sum
  • 原文地址:https://www.cnblogs.com/shenjianping/p/15903013.html
Copyright © 2020-2023  润新知