Files
open-im-server/pkg/common/cmd/root.go
T

81 lines
1.8 KiB
Go
Raw Normal View History

2023-03-07 12:12:16 +08:00
package cmd
import (
2023-03-07 17:59:34 +08:00
"OpenIM/pkg/common/config"
"OpenIM/pkg/common/constant"
2023-03-07 12:12:16 +08:00
"github.com/spf13/cobra"
)
2023-03-07 18:06:57 +08:00
type RootCmd struct {
2023-03-07 19:56:22 +08:00
Command cobra.Command
port int
portFlag bool
prometheusPort int
prometheusPortFlag bool
2023-03-07 18:06:57 +08:00
}
2023-03-07 17:59:34 +08:00
2023-03-07 19:56:22 +08:00
func NewRootCmd() RootCmd {
2023-03-07 17:59:34 +08:00
c := cobra.Command{
2023-03-07 12:12:16 +08:00
Use: "start",
Short: "Start the server",
Long: `Start the server`,
}
2023-03-07 19:56:22 +08:00
rootCmd := RootCmd{}
c.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if rootCmd.portFlag {
rootCmd.port = rootCmd.getPortFlag(cmd)
}
if rootCmd.prometheusPortFlag {
rootCmd.prometheusPort = rootCmd.GetPrometheusPortFlag(cmd)
}
return rootCmd.getConfFromCmdAndInit(cmd)
}
2023-03-07 18:06:57 +08:00
rootCmd.init()
2023-03-07 20:07:44 +08:00
rootCmd.Command = c
2023-03-07 18:06:57 +08:00
return rootCmd
2023-03-07 17:59:34 +08:00
}
2023-03-07 20:12:36 +08:00
func (r *RootCmd) AddRunE(f func(cmd RootCmd) error) {
2023-03-07 19:56:22 +08:00
r.Command.RunE = func(cmd *cobra.Command, args []string) error {
2023-03-07 20:12:36 +08:00
return f(*r)
2023-03-07 19:56:22 +08:00
}
}
2023-03-07 20:12:36 +08:00
func (r *RootCmd) init() {
2023-03-07 18:06:57 +08:00
r.Command.Flags().StringP(constant.FlagConf, "c", "", "Path to config file folder")
2023-03-07 17:59:34 +08:00
}
2023-03-07 20:12:36 +08:00
func (r *RootCmd) AddPortFlag() {
2023-03-07 19:56:22 +08:00
r.Command.Flags().StringP(constant.FlagPort, "p", "", "server listen port")
r.portFlag = true
}
2023-03-07 20:12:36 +08:00
func (r *RootCmd) getPortFlag(cmd *cobra.Command) int {
2023-03-07 19:56:22 +08:00
port, _ := cmd.Flags().GetInt(constant.FlagPort)
return port
}
2023-03-07 20:12:36 +08:00
func (r *RootCmd) GetPortFlag() int {
2023-03-07 19:56:22 +08:00
return r.port
}
2023-03-07 20:12:36 +08:00
func (r *RootCmd) AddPrometheusPortFlag() {
2023-03-07 19:56:22 +08:00
r.Command.Flags().StringP(constant.PrometheusPort, "pp", "", "server listen port")
r.prometheusPortFlag = true
}
2023-03-07 20:12:36 +08:00
func (r *RootCmd) GetPrometheusPortFlag(cmd *cobra.Command) int {
2023-03-07 19:56:22 +08:00
port, _ := cmd.Flags().GetInt(constant.PrometheusPort)
return port
}
2023-03-07 20:12:36 +08:00
func (r *RootCmd) getConfFromCmdAndInit(cmdLines *cobra.Command) error {
2023-03-07 17:59:34 +08:00
configFolderPath, _ := cmdLines.Flags().GetString(constant.FlagConf)
return config.InitConfig(configFolderPath)
2023-03-07 12:12:16 +08:00
}
2023-03-07 20:07:13 +08:00
2023-03-07 20:12:36 +08:00
func (r *RootCmd) Execute() error {
2023-03-07 20:07:13 +08:00
return r.Command.Execute()
}