package cmd import ( "fmt" "github.com/spf13/cobra" "log" "net/http" "os" "picgo/configs" "picgo/corelib" "picgo/model" "picgo/router" "strings" ) var rootCmd = &cobra.Command{ Use: "root", PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) { fmt.Println("args:") fmt.Println(strings.Join(args, " ")) if len(os.Args) < 1 { log.Panic("请指定配置文件路径") return } configFile := args[0] fmt.Println("配置文件路径: ", configFile) // 初始化配置文件 configs.NewConfig(configFile) // 初始化日志 corelib.NewLogger() // 初始化redis corelib.NewRedis() // 初始化mysql corelib.NewMysql() // 初始化session store corelib.NewSessionStore() return }, } var picgoCmd = &cobra.Command{ Use: "picgo", Run: func(cmd *cobra.Command, args []string) { // 创建路由 router.InitRouter() // 启动HTTP服务器 corelib.Logger.Infoln("Serving on http://", fmt.Sprintf("%s:%d", configs.Settings.Server.Host, configs.Settings.Server.Port)) err := http.ListenAndServe(fmt.Sprintf("%s:%d", configs.Settings.Server.Host, configs.Settings.Server.Port), nil) if err != nil { log.Fatalf("Failed to start server: %v", err) } }, } var MigrateCmd = &cobra.Command{ Use: "migrate", Run: func(cmd *cobra.Command, args []string) { var err error // 自动迁移数据库 if err = corelib.DbMysql.AutoMigrate(&model.SysUser{}); err != nil { panic("SysUser 迁移数据库失败") } if err = corelib.DbMysql.AutoMigrate(&model.Domain{}); err != nil { panic("Domain 迁移数据库失败") } if err = corelib.DbMysql.AutoMigrate(&model.Upload{}); err != nil { panic("Upload 迁移数据库失败") } // 初始化管理员用户 err = initSysUser() if err != nil { fmt.Println("初始化管理员用户失败", err) } }, } func init() { rootCmd.AddCommand(picgoCmd) rootCmd.AddCommand(MigrateCmd) } func Execute() { err := rootCmd.Execute() if err != nil { return } } // 初始化超级管理员 func initSysUser() error { var ( hashPassword string err error ) userName := "admin001" password := "Admin#123456" salt := corelib.GenerateSalt() if hashPassword, err = corelib.HashPassword(password, salt); err != nil { corelib.Logger.Errorln("initSystem 生成密码失败: ", err) return err } user := model.SysUser{Username: userName, Password: hashPassword, Salt: salt, IsSuper: 1} if err = corelib.DbMysql.Create(&user).Error; err != nil { corelib.Logger.Errorln("initSystem 初始化管理员用户失败: ", err) return err } return nil }