2023-02-03 16:18:31 +08:00
|
|
|
|
package cmd
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2023-05-13 01:27:48 +08:00
|
|
|
|
"demo-server/cmd/inits"
|
|
|
|
|
"demo-server/internal/config"
|
2023-05-13 00:55:47 +08:00
|
|
|
|
"demo-server/internal/model"
|
|
|
|
|
"demo-server/internal/server"
|
2023-05-13 01:27:48 +08:00
|
|
|
|
"fmt"
|
2023-02-03 16:18:31 +08:00
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
|
"go.uber.org/zap"
|
|
|
|
|
"os"
|
|
|
|
|
"os/signal"
|
|
|
|
|
"syscall"
|
|
|
|
|
)
|
|
|
|
|
|
2023-05-13 01:27:48 +08:00
|
|
|
|
|
2023-02-03 16:18:31 +08:00
|
|
|
|
// 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",
|
2023-05-13 01:27:48 +08:00
|
|
|
|
Long: `server run,default on ` + model.DefaultServerAddress + `
|
|
|
|
|
flag: -d don't run stub'
|
|
|
|
|
`,
|
|
|
|
|
Run: runSvr,
|
2023-02-03 16:18:31 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
|
rootCmd.AddCommand(svrCmd)
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-13 01:27:48 +08:00
|
|
|
|
// runSvr 启动 server
|
|
|
|
|
func runSvr(_ *cobra.Command, _ []string) {
|
|
|
|
|
if err := inits.InitServer(); err != nil {
|
|
|
|
|
panic(fmt.Errorf("init svr err, cause: %w", err))
|
2023-02-03 16:18:31 +08:00
|
|
|
|
}
|
2023-05-13 01:27:48 +08:00
|
|
|
|
runServer()
|
2023-02-03 16:18:31 +08:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-13 01:27:48 +08:00
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-03 16:18:31 +08:00
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
|
2023-05-13 01:27:48 +08:00
|
|
|
|
//ka := kafka.NewManager(ctx, conf.Kafka)
|
|
|
|
|
//svc.SetKafka(ka)
|
|
|
|
|
svr := server.New(conf)
|
2023-02-03 16:18:31 +08:00
|
|
|
|
|
2023-05-13 01:27:48 +08:00
|
|
|
|
go svr.Run()
|
|
|
|
|
svr.SvrRunSuccessMsg()
|
2023-02-03 16:18:31 +08:00
|
|
|
|
|
|
|
|
|
defer func() {
|
2023-05-13 01:27:48 +08:00
|
|
|
|
if err := svr.Shutdown(ctx); err != nil {
|
|
|
|
|
zap.S().Error(err)
|
2023-02-03 16:18:31 +08:00
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
|
2023-05-13 01:27:48 +08:00
|
|
|
|
signalWatch(ctx, cancel)
|
2023-02-03 16:18:31 +08:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-13 01:27:48 +08:00
|
|
|
|
// signalWatch 阻塞主进程
|
|
|
|
|
func signalWatch(ctx context.Context, cancel context.CancelFunc) {
|
2023-02-03 16:18:31 +08:00
|
|
|
|
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")
|
|
|
|
|
}
|
|
|
|
|
}
|