package cmd import ( "context" "demo-server/cmd/inits" "demo-server/internal/config" "demo-server/internal/model" "demo-server/internal/server" "fmt" "github.com/spf13/cobra" "go.uber.org/zap" "os" "os/signal" "syscall" ) // svrCmd represents the svr command // go build -ldflags "-w -s" -o packet-admin.out . && ./packet-admin.out svr var svrCmd = &cobra.Command{ Use: "svr", Short: "server run", Long: `server run,default on ` + model.DefaultServerAddress + ` flag: -d don't run stub' `, Run: runSvr, } func init() { rootCmd.AddCommand(svrCmd) } // runSvr 启动 server func runSvr(_ *cobra.Command, _ []string) { if err := inits.InitServer(); err != nil { panic(fmt.Errorf("init svr err, cause: %w", err)) } runServer() } func runServer() { conf := config.Get() svc := inits.GetSvcPolymer() if conf == nil || conf.Svr == nil || svc == nil { zap.S().Error("server conf nil!", inits.ErrorInitFundamental) return } ctx, cancel := context.WithCancel(context.Background()) //ka := kafka.NewManager(ctx, conf.Kafka) //svc.SetKafka(ka) svr := server.New(conf) go svr.Run() svr.SvrRunSuccessMsg() defer func() { if err := svr.Shutdown(ctx); err != nil { zap.S().Error(err) } }() signalWatch(ctx, cancel) } // signalWatch 阻塞主进程 func signalWatch(ctx context.Context, cancel context.CancelFunc) { sigterm := make(chan os.Signal, 1) signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM) select { case <-ctx.Done(): zap.S().Infof("terminating: context cancelled") case <-sigterm: cancel() zap.S().Infof("terminating: via signal") } }