1 Star 0 Fork 0

玟兵 / go-util

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
httpsrv.go 857 Bytes
一键复制 编辑 原始数据 按行查看 历史
玟兵 提交于 2024-04-29 17:06 . Redis 优化
package util
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
// HttpSrvRun 使用 http.Server 内置的 Shutdown() 方法优雅地关机
func HttpSrvRun(addr string, hdl http.Handler, onClose func()) {
srv := &http.Server{
Addr: addr,
Handler: hdl,
}
if onClose != nil {
srv.RegisterOnShutdown(onClose)
}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %s\n", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
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")
}
Go
1
https://gitee.com/binny_w/go-util.git
git@gitee.com:binny_w/go-util.git
binny_w
go-util
go-util
master

搜索帮助