annotation/cmd/server.go

120 lines
3.1 KiB
Go
Raw Permalink Normal View History

2023-05-12 16:53:21 +08:00
package cmd
import (
"context"
"fmt"
"git.hpds.cc/Component/logging"
"github.com/spf13/cobra"
"go.uber.org/zap"
"hpds_annotation/config"
"hpds_annotation/global"
router2 "hpds_annotation/internal/router"
"hpds_annotation/mq"
"hpds_annotation/store"
"net/http"
"os"
"os/signal"
"syscall"
)
var (
ConfigFileFlag string = "./config/config.yaml"
NodeName string = "edge-node"
Mode string = "dev"
)
func must(err error) {
if err != nil {
_, _ = fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
}
func NewStartCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "start",
Short: "Start hpds_web application",
Run: func(cmd *cobra.Command, args []string) {
var (
cfg *config.WebConfig
err error
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
must(err)
configFileFlag, err := cmd.Flags().GetString("c")
if err != nil {
fmt.Println("get local config err: ", err)
return
}
NodeName, err = cmd.Flags().GetString("n")
if err != nil {
fmt.Println("get remote path config err: ", err)
return
}
Mode, err = cmd.Flags().GetString("m")
if err != nil {
fmt.Println("get remote path config err: ", err)
return
}
cfg, err = config.ParseConfigByFile(configFileFlag)
must(err)
global.Cfg = cfg
global.Logger = LoadLoggerConfig(cfg.Logging)
logger := LoadLoggerConfig(cfg.Logging)
global.FileLabelList = store.Load(cfg.TempPath)
//创建消息连接点
mq.MqList, err = mq.NewMqClient(cfg.Funcs, cfg.Node, logger)
must(err)
// 退出channel
exitChannel := make(chan os.Signal)
defer close(exitChannel)
router := router2.InitRouter(cfg, logger)
// 退出信号监听
go func(c chan os.Signal) {
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
}(exitChannel)
go func() {
fmt.Printf("Http Server start at port %d \n", cfg.Port)
err = http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), router)
must(err)
}()
select {
case <-ctx.Done():
store.Save(cfg.TempPath, global.FileLabelList)
logger.With(
zap.String("web", "exit"),
).Error(ctx.Err().Error())
return
case errs := <-exitChannel:
store.Save(cfg.TempPath, global.FileLabelList)
logger.With(
zap.String("web", "服务退出"),
).Info(errs.String())
return
}
},
}
cmd.Flags().StringVar(&ConfigFileFlag, "c", "./config/config.yaml", "The configuration file path")
cmd.Flags().StringVar(&NodeName, "n", "main-node", "The configuration name")
cmd.Flags().StringVar(&Mode, "m", "dev", "run mode : dev | test | releases")
return cmd
}
func LoadLoggerConfig(opt config.LogOptions) *logging.Logger {
return logging.NewLogger(
logging.SetPath(opt.Path),
logging.SetPrefix(opt.Prefix),
logging.SetDevelopment(opt.Development),
logging.SetDebugFileSuffix(opt.DebugFileSuffix),
logging.SetWarnFileSuffix(opt.WarnFileSuffix),
logging.SetErrorFileSuffix(opt.ErrorFileSuffix),
logging.SetInfoFileSuffix(opt.InfoFileSuffix),
logging.SetMaxAge(opt.MaxAge),
logging.SetMaxBackups(opt.MaxBackups),
logging.SetMaxSize(opt.MaxSize),
logging.SetLevel(logging.LogLevel["debug"]),
)
}