main.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/spf13/cobra"
  6. "github.com/runningwater/gohub/app/cmd"
  7. "github.com/runningwater/gohub/bootstrap"
  8. appConfig "github.com/runningwater/gohub/config"
  9. "github.com/runningwater/gohub/pkg/config"
  10. "github.com/runningwater/gohub/pkg/console"
  11. )
  12. func init() {
  13. // 加载 config 目录下的配置信息
  14. appConfig.Initialize()
  15. }
  16. func main() {
  17. // 应用主入口,默认调用 cmd.CmdServe 命令
  18. // 该命令会启动 HTTP 服务
  19. var rootCmd = &cobra.Command{
  20. Use: "gohub",
  21. Short: "gohub is a simple forum project",
  22. Long: `Default will run "serve" command, you can use "-h" flag to see all subcommands`,
  23. // 所有子命令都会调用以下代码来初始化配置信息
  24. PersistentPreRun: func(command *cobra.Command, args []string) {
  25. // 配置初始化,依赖命令行 --env 参数
  26. config.InitConfig(cmd.Env)
  27. // 初始化 Logger
  28. bootstrap.SetupLogger()
  29. // 初始化 DB
  30. // 注意: 初始化 DB 前应该先初始化 logger
  31. bootstrap.SetupDB()
  32. // 初始化 Redis
  33. bootstrap.SetupRedis()
  34. },
  35. }
  36. // 注册子命令
  37. rootCmd.AddCommand(
  38. cmd.CmdServe,
  39. cmd.CmdKey,
  40. cmd.CmdPlay,
  41. )
  42. // 配置默认运行 Web 服务
  43. cmd.RegisterDefaultCmd(rootCmd, cmd.CmdServe)
  44. // 注册全局参数 --env
  45. cmd.RegisterGlobalFlags(rootCmd)
  46. // 执行主命令
  47. if err := rootCmd.Execute(); err != nil {
  48. console.Exit(fmt.Sprintf("Failed to run app with %v: %s", os.Args, err.Error()))
  49. }
  50. }