//平滑启动为了 防止重启时或者更新包时 直接杀掉原来的进程导致正在运行的操作被中断
package main
import (
"context"
"github.com/gin-gonic/gin"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
var i = 0
func main() {
router := gin.Default()
//创建两个接口,一个延迟9秒钟返回信息
router.GET("/", func(c *gin.Context) {
time.Sleep(20 * time.Second)
i++
c.JSON(http.StatusOK,gin.H{
"num":i,
})
})
//一个立刻返回信息
router.GET("/a", func(c *gin.Context) {
i++
c.JSON(http.StatusOK,gin.H{
"num":"aaa",
})
})
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 && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
//创建一个信号监听通道
quit := make(chan os.Signal, 1)
//监听 syscall.SIGINT 跟 syscall.SIGTERM信号
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
si :=<-quit
log.Println("Shutting down server...",si)
//shutdown方法需要传入一个上下文参数,这里就设计到两种用法
//1.WithCancel带时间,表示接收到信号之后,过完该断时间不管当前请求是否完成,强制断开
//ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
//2.不带时间,表示等待当前请求全部完成再断开
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
//当请求还在的时候强制断开了连接将产生错误,err不为空
log.Fatal("Server forced to shutdown:", err)
}
log.Println("Server exiting")
}