From b7c3d256ebd4f35e59a65dbbbcea252ebd02bf99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B0=E4=BA=AE?= Date: Wed, 28 Aug 2019 19:26:51 +0800 Subject: [PATCH] =?UTF-8?q?Add=20=E4=BC=98=E9=9B=85=E5=9C=B0=E9=87=8D?= =?UTF-8?q?=E5=90=AF=E6=88=96=E5=81=9C=E6=AD=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 42 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/main.go b/main.go index fde8195..d5467bc 100644 --- a/main.go +++ b/main.go @@ -1,26 +1,52 @@ package main import ( + "context" + "fmt" "github.com/gin-gonic/gin" "go-gin-api/app/config" "go-gin-api/app/route" "log" + "net/http" "os" + "os/signal" + "time" ) func main() { - - //gin.DebugMode 测试模式 - //gin.ReleaseMode 发布模式 - gin.SetMode(gin.DebugMode) + gin.SetMode(config.AppMode) engine := gin.New() // 设置路由 route.SetupRouter(engine) - // 启动服务 - if err := engine.Run(config.AppPort); err != nil { - log.Println(err) - os.Exit(1) + server := &http.Server{ + Addr : config.AppPort, + Handler : engine, + ReadTimeout : config.AppReadTimeout * time.Second, + WriteTimeout : config.AppWriteTimeout * time.Second, } + + info := fmt.Sprintf("HTTP server listening %s, Pid is %v ", config.AppPort, os.Getpid()) + fmt.Println(info) + + go func() { + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("HTTP server listen: %s\n", err) + } + }() + + // 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间) + signalChan := make(chan os.Signal) + signal.Notify(signalChan, os.Interrupt) + sig := <-signalChan + log.Println("Get Signal:", sig) + log.Println("Shutdown Server ...") + + ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second) + defer cancel() + if err := server.Shutdown(ctx); err != nil { + log.Fatal("Server Shutdown:", err) + } + log.Println("Server exiting") }