Skip to content

Commit

Permalink
Merge pull request #32 from zjutjh/SugarMGP/dev
Browse files Browse the repository at this point in the history
refactor: 实现优雅停止
  • Loading branch information
Penryn authored Dec 8, 2024
2 parents 62e46cb + 8698d4e commit 66d5a75
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 4 deletions.
50 changes: 50 additions & 0 deletions app/utils/server/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package server

import (
"context"
"errors"
"net/http"
"os"
"os/signal"
"time"

"4u-go/config/redis"
"go.uber.org/zap"
)

// Run 运行 http 服务器
func Run(handler http.Handler, addr string) {
srv := &http.Server{
Addr: addr,
Handler: handler,
ReadHeaderTimeout: 2 * time.Second,
}

// 启动服务器协程
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
zap.L().Fatal("Server Error Occurred", zap.Error(err))
}
}()

// 阻塞并监听结束信号
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit

zap.L().Info("Shutdown Server...")

// 关闭服务器(5秒超时时间)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
zap.L().Error("Server Shutdown Failed", zap.Error(err))
}

// 关闭 Redis 客户端
if err := redis.GlobalClient.Close(); err != nil {
zap.L().Error("Redis Client Shutdown Failed", zap.Error(err))
}

zap.L().Info("Server Closed")
}
6 changes: 2 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"4u-go/app/midwares"
"4u-go/app/utils/aes"
"4u-go/app/utils/log"
"4u-go/app/utils/server"
"4u-go/config/config"
"4u-go/config/database"
"4u-go/config/objectStorage"
Expand Down Expand Up @@ -43,8 +44,5 @@ func main() {
wechat.Init()
router.Init(r)

err := r.Run(":" + config.Config.GetString("server.port"))
if err != nil {
zap.L().Fatal(err.Error())
}
server.Run(r, ":"+config.Config.GetString("server.port"))
}

0 comments on commit 66d5a75

Please sign in to comment.