优化服务启动流程

This commit is contained in:
2025-05-14 15:13:44 +08:00
parent d69a77df38
commit f86cf47e86
7 changed files with 243 additions and 123 deletions

View File

@@ -2,38 +2,42 @@ package web
import (
"context"
"log/slog"
"net/http"
"proxy-server/server/pkg/env"
"strconv"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
var server *http.Server
type Server struct {
http *http.Server
}
func Start(ctx context.Context) error {
func New() *Server {
return &Server{}
}
func (s *Server) Run() error {
address := ":" + strconv.Itoa(int(env.AppWebPort))
engine := gin.Default()
server = &http.Server{Addr: address, Handler: engine}
s.http = &http.Server{Addr: address, Handler: engine}
// 配置中间件和路由
Router(engine)
// 监听关闭信号
go func() {
<-ctx.Done()
err := server.Shutdown(context.Background())
if err != nil {
slog.Error("web 服务关闭失败", err)
}
}()
// 启动服务
err := server.ListenAndServe()
err := s.http.ListenAndServe()
if err != nil {
return errors.Wrap(err, "web 服务启动失败")
return err
}
return nil
}
func (s *Server) Stop() error {
err := s.http.Shutdown(context.Background())
if err != nil {
return err
}
return nil