viper-app/cmd/svr.go

79 lines
1.6 KiB
Go
Raw Normal View History

2023-02-03 16:18:31 +08:00
package cmd
import (
"context"
"demo-server/cmd/inits"
"demo-server/internal/config"
"demo-server/internal/model"
"demo-server/internal/server"
"fmt"
2023-02-03 16:18:31 +08:00
"github.com/spf13/cobra"
"go.uber.org/zap"
"os"
"os/signal"
"syscall"
)
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",
Long: `server rundefault on ` + model.DefaultServerAddress + `
flag: -d don't run stub'
`,
Run: runSvr,
2023-02-03 16:18:31 +08:00
}
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))
2023-02-03 16:18:31 +08:00
}
runServer()
2023-02-03 16:18:31 +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())
//ka := kafka.NewManager(ctx, conf.Kafka)
//svc.SetKafka(ka)
svr := server.New(conf)
2023-02-03 16:18:31 +08:00
go svr.Run()
svr.SvrRunSuccessMsg()
2023-02-03 16:18:31 +08:00
defer func() {
if err := svr.Shutdown(ctx); err != nil {
zap.S().Error(err)
2023-02-03 16:18:31 +08:00
}
}()
signalWatch(ctx, cancel)
2023-02-03 16:18:31 +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")
}
}