package server import ( "context" "github.com/gin-gonic/gin" "go.uber.org/zap" "net" "net/http" "packet-ui/internal/model" "packet-ui/internal/model/server" "time" ) type Server struct { cfg *model.Configuration *gin.Engine } var ( svr *Server ) func GetSvr() *Server { return svr } func NewSvr(cfg *model.Configuration) *Server { s := &Server{ cfg: cfg, } s.Init(InitEngine, InitRouter) svr = s return s } // RunServer 如果初始化失败 cancel func RunServer(cfg *model.Configuration, cancel context.CancelFunc) (httpServer *http.Server) { s := NewSvr(cfg) svrConfig := cfg.Svr defer func() { if r := recover(); r != nil { cancel() } else { serverRunSuccess(svrConfig) } }() httpSvr := &http.Server{ Addr: svrConfig.Address, Handler: s.Engine, ReadTimeout: 120 * time.Second, WriteTimeout: 120 * time.Second, MaxHeaderBytes: 1 << 20, } httpServer = httpSvr go func() { if err := httpSvr.ListenAndServe(); err != nil && err != http.ErrServerClosed { zap.S().Panicf("run server err! %v", err) } }() return } func serverRunSuccess(svr *server.Config) { printIPInfo := func(adds ...string) { info := "svr running, via" for _, add := range adds { info += "\n\thttp://" + add } zap.S().Info(info) } ip, port, _ := net.SplitHostPort(svr.Address) adders, err := net.InterfaceAddrs() if net.ParseIP(ip).IsUnspecified() && err == nil { var successAddress []string for _, addr := range adders { if ipNet, ok := addr.(*net.IPNet); ok { successAddress = append(successAddress, net.JoinHostPort(ipNet.IP.String(), port)) } } printIPInfo(successAddress...) } else { printIPInfo(svr.Address) } } // Dispatch 当配置文件更新的时候可以去调用 // 目前使用的全局 config 指针的方式如果发生更改,理论上 server 关联的 model 内置指针对象也会被更改 // 需要重新初始化的部分将由本函数予以实现 func (s *Server) Dispatch(_ *model.Configuration) { }