hpds_jkw_web/cmd/server.go

155 lines
4.2 KiB
Go
Raw Normal View History

2023-01-06 10:09:23 +08:00
package cmd
import (
"context"
"fmt"
"github.com/spf13/cobra"
"go.uber.org/zap"
"hpds-iot-web/config"
router2 "hpds-iot-web/internal/router"
"hpds-iot-web/model"
discover "hpds-iot-web/pkg/discover/consul"
"net/http"
"os"
"os/signal"
"syscall"
2023-01-06 19:15:52 +08:00
"git.hpds.cc/Component/logging"
2023-01-06 10:09:23 +08:00
)
var (
//consulConfigs chan *discover.ConsulConfig
ConfigFileFlag string = "./config/config.yaml"
ConsulAddress string = "http://localhost:8500"
NodeName string = "main-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
}
ConsulAddress, err = cmd.Flags().GetString("r")
if err != nil {
fmt.Println("get remote 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
}
if len(configFileFlag) > 1 {
cfg, err = config.ParseConfigByFile(configFileFlag)
must(err)
err = config.UpdateRemoteConfig(cfg)
must(err)
ConfigFileFlag = configFileFlag
} else {
//获取consul注册中心的配置文件
cfg, err = config.GetRemoteConfig(ConsulAddress, fmt.Sprintf("hpds-pavement/hpds_web/%s/%s", Mode, NodeName))
must(err)
err = config.UpdateLocalConfig(cfg, ConfigFileFlag)
}
//创建注册对象
tags := make([]string, 1)
tags[0] = "web"
consulCfg, err := discover.NewConsulConfig(cfg.Consul.Host, cfg.Name, cfg.Name, cfg.Consul.Host, cfg.Consul.Port,
tags, 300, 300, 300)
must(err)
//连接数据库
model.New(cfg.Db.DriveName, cfg.Db.Conn)
//连接redis
model.NewCache(cfg.Cache)
2023-01-06 19:15:52 +08:00
logger := LoadLoggerConfig(cfg.Logging)
2023-01-06 10:09:23 +08:00
// 退出channel
exitChannel := make(chan os.Signal)
defer close(exitChannel)
// 退出信号监听
go func(c chan os.Signal) {
consulCfg.ServiceDeregister()
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
}(exitChannel)
2023-01-06 19:15:52 +08:00
router := router2.InitRouter(logger, model.DB)
2023-01-06 10:09:23 +08:00
// start http service
go func() {
fmt.Printf("Http Server start at port %d \n", cfg.Port)
//启动前执行注册
err = consulCfg.ServiceRegister()
must(err)
err = http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), router)
must(err)
}()
//服务退出取消注册
//err = consulCfg.ServiceDeregister()
//
//must(err)
//zap.L().Error("发生错误", zap.Error(err))
select {
case <-ctx.Done():
consulCfg.ServiceDeregister()
2023-01-06 19:15:52 +08:00
logger.With(
2023-01-06 10:09:23 +08:00
zap.String("web", "exit"),
).Error(ctx.Err().Error())
return
case errs := <-exitChannel:
consulCfg.ServiceDeregister()
2023-01-06 19:15:52 +08:00
logger.With(
zap.String("web", "服务退出"),
).Info(errs.String())
2023-01-06 10:09:23 +08:00
return
}
},
}
cmd.Flags().StringVar(&ConfigFileFlag, "c", "./config/config.yaml", "The configuration file path")
cmd.Flags().StringVar(&ConsulAddress, "r", "http://consul.hpds.cc", "The configuration remote consul address")
cmd.Flags().StringVar(&NodeName, "n", "main-node", "The configuration name")
cmd.Flags().StringVar(&Mode, "m", "dev", "run mode : dev | test | releases")
return cmd
}
2023-01-06 19:15:52 +08:00
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"]),
)
}