// LoadGlobalConfig loads Hugo configuration into the global Viper. func LoadGlobalConfig(relativeSourcePath, configFilename string) error { if relativeSourcePath == "" { relativeSourcePath = "." } viper.AutomaticEnv() viper.SetEnvPrefix("hugo") viper.SetConfigFile(configFilename) // See https://github.com/spf13/viper/issues/73#issuecomment-126970794 if relativeSourcePath == "" { viper.AddConfigPath(".") } else { viper.AddConfigPath(relativeSourcePath) } err := viper.ReadInConfig() if err != nil { if _, ok := err.(viper.ConfigParseError); ok { return err } return fmt.Errorf("Unable to locate Config file. Perhaps you need to create a new site.\n Run `hugo help new` for details. (%s)\n", err) } viper.RegisterAlias("indexes", "taxonomies") loadDefaultSettings() return nil }
// InitializeConfig initializes a config file with sensible default configuration flags. func InitializeConfig() { // viper.SetConfigFile(CfgFile) viper.RegisterAlias("indexes", "taxonomies") LoadDefaultSettings() if ipvanishCmdV.PersistentFlags().Lookup("sort").Changed { viper.Set("sort", Sort) } //log.Debugf("Using config file: %s", viper.ConfigFileUsed()) }
// TODO: Need to look at whether this is just too much going on. func init() { // enable ability to specify config file via flag RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.trackello.yaml)") if cfgFile != "" { viper.SetConfigFile(cfgFile) } viper.SetConfigName(".trackello") // name of config file (without extension) // Set Environment Variables viper.SetEnvPrefix("trackello") viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) // replace environment variables to underscore (_) from hyphen (-) if err := viper.BindEnv("appkey", trackello.TRACKELLO_APPKEY); err != nil { panic(err) } if err := viper.BindEnv("token", trackello.TRACKELLO_TOKEN); err != nil { panic(err) } if err := viper.BindEnv("board", trackello.TRACKELLO_PREFERRED_BOARD); err != nil { panic(err) } viper.AutomaticEnv() // read in environment variables that match every time Get() is called // Add Configuration Paths if cwd, err := os.Getwd(); err == nil { viper.AddConfigPath(cwd) } viper.AddConfigPath("$HOME") // adding home directory as first search path // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } RootCmd.AddCommand(configCmd) RootCmd.PersistentFlags().StringVar(&trelloAppKey, "appkey", "", "Trello Application Key") if err := viper.BindPFlag("appkey", RootCmd.PersistentFlags().Lookup("appkey")); err != nil { panic(err) } RootCmd.PersistentFlags().StringVar(&trelloToken, "token", "", "Trello Token") if err := viper.BindPFlag("token", RootCmd.PersistentFlags().Lookup("token")); err != nil { panic(err) } RootCmd.PersistentFlags().StringVar(&preferredBoard, "board", "", "Preferred Board ID") if err := viper.BindPFlag("board", RootCmd.PersistentFlags().Lookup("board")); err != nil { panic(err) } viper.RegisterAlias("preferredBoard", "board") }
// InitializeConfig initializes a config file with sensible default configuration flags. // A Hugo command that calls initCoreCommonFlags() can pass itself // as an argument to have its command-line flags processed here. func InitializeConfig(subCmdVs ...*cobra.Command) error { viper.SetConfigFile(cfgFile) // See https://github.com/spf13/viper/issues/73#issuecomment-126970794 if source == "" { viper.AddConfigPath(".") } else { viper.AddConfigPath(source) } err := viper.ReadInConfig() if err != nil { if _, ok := err.(viper.ConfigParseError); ok { return newSystemError(err) } else { return newSystemErrorF("Unable to locate Config file. Perhaps you need to create a new site.\n Run `hugo help new` for details. (%s)\n", err) } } viper.RegisterAlias("indexes", "taxonomies") LoadDefaultSettings() for _, cmdV := range append([]*cobra.Command{hugoCmdV}, subCmdVs...) { if flagChanged(cmdV.PersistentFlags(), "verbose") { viper.Set("Verbose", verbose) } if flagChanged(cmdV.PersistentFlags(), "logFile") { viper.Set("LogFile", logFile) } if flagChanged(cmdV.Flags(), "cleanDestinationDir") { viper.Set("cleanDestinationDir", cleanDestination) } if flagChanged(cmdV.Flags(), "buildDrafts") { viper.Set("BuildDrafts", draft) } if flagChanged(cmdV.Flags(), "buildFuture") { viper.Set("BuildFuture", future) } if flagChanged(cmdV.Flags(), "uglyURLs") { viper.Set("UglyURLs", uglyURLs) } if flagChanged(cmdV.Flags(), "canonifyURLs") { viper.Set("CanonifyURLs", canonifyURLs) } if flagChanged(cmdV.Flags(), "disableRSS") { viper.Set("DisableRSS", disableRSS) } if flagChanged(cmdV.Flags(), "disableSitemap") { viper.Set("DisableSitemap", disableSitemap) } if flagChanged(cmdV.Flags(), "disableRobotsTXT") { viper.Set("DisableRobotsTXT", disableRobotsTXT) } if flagChanged(cmdV.Flags(), "pluralizeListTitles") { viper.Set("PluralizeListTitles", pluralizeListTitles) } if flagChanged(cmdV.Flags(), "preserveTaxonomyNames") { viper.Set("PreserveTaxonomyNames", preserveTaxonomyNames) } if flagChanged(cmdV.Flags(), "ignoreCache") { viper.Set("IgnoreCache", ignoreCache) } if flagChanged(cmdV.Flags(), "forceSyncStatic") { viper.Set("ForceSyncStatic", forceSync) } if flagChanged(cmdV.Flags(), "noTimes") { viper.Set("NoTimes", noTimes) } } if baseURL != "" { if !strings.HasSuffix(baseURL, "/") { baseURL = baseURL + "/" } viper.Set("BaseURL", baseURL) } if !viper.GetBool("RelativeURLs") && viper.GetString("BaseURL") == "" { jww.ERROR.Println("No 'baseurl' set in configuration or as a flag. Features like page menus will not work without one.") } if theme != "" { viper.Set("theme", theme) } if destination != "" { viper.Set("PublishDir", destination) } if source != "" { dir, _ := filepath.Abs(source) viper.Set("WorkingDir", dir) } else { dir, _ := os.Getwd() viper.Set("WorkingDir", dir) } if contentDir != "" { viper.Set("ContentDir", contentDir) } if layoutDir != "" { viper.Set("LayoutDir", layoutDir) } if cacheDir != "" { if helpers.FilePathSeparator != cacheDir[len(cacheDir)-1:] { cacheDir = cacheDir + helpers.FilePathSeparator } isDir, err := helpers.DirExists(cacheDir, hugofs.SourceFs) utils.CheckErr(err) if isDir == false { mkdir(cacheDir) } viper.Set("CacheDir", cacheDir) } else { viper.Set("CacheDir", helpers.GetTempDir("hugo_cache", hugofs.SourceFs)) } if verboseLog || logging || (viper.IsSet("LogFile") && viper.GetString("LogFile") != "") { if viper.IsSet("LogFile") && viper.GetString("LogFile") != "" { jww.SetLogFile(viper.GetString("LogFile")) } else { jww.UseTempLogFile("hugo") } } else { jww.DiscardLogging() } if viper.GetBool("verbose") { jww.SetStdoutThreshold(jww.LevelInfo) } if verboseLog { jww.SetLogThreshold(jww.LevelInfo) } jww.INFO.Println("Using config file:", viper.ConfigFileUsed()) themeDir := helpers.GetThemeDir() if themeDir != "" { if _, err := os.Stat(themeDir); os.IsNotExist(err) { return newSystemError("Unable to find theme Directory:", themeDir) } } themeVersionMismatch, minVersion := isThemeVsHugoVersionMismatch() if themeVersionMismatch { jww.ERROR.Printf("Current theme does not support Hugo version %s. Minimum version required is %s\n", helpers.HugoReleaseVersion(), minVersion) } return nil }
// InitializeConfig initializes a config file with sensible default configuration flags. func InitializeConfig() { viper.SetConfigFile(CfgFile) viper.AddConfigPath(Source) err := viper.ReadInConfig() if err != nil { jww.ERROR.Println("Unable to locate Config file. Perhaps you need to create a new site. Run `hugo help new` for details") } viper.RegisterAlias("indexes", "taxonomies") LoadDefaultSettings() if hugoCmdV.PersistentFlags().Lookup("buildDrafts").Changed { viper.Set("BuildDrafts", Draft) } if hugoCmdV.PersistentFlags().Lookup("buildFuture").Changed { viper.Set("BuildFuture", Future) } if hugoCmdV.PersistentFlags().Lookup("uglyUrls").Changed { viper.Set("UglyURLs", UglyURLs) } if hugoCmdV.PersistentFlags().Lookup("disableRSS").Changed { viper.Set("DisableRSS", DisableRSS) } if hugoCmdV.PersistentFlags().Lookup("disableSitemap").Changed { viper.Set("DisableSitemap", DisableSitemap) } if hugoCmdV.PersistentFlags().Lookup("verbose").Changed { viper.Set("Verbose", Verbose) } if hugoCmdV.PersistentFlags().Lookup("pluralizeListTitles").Changed { viper.Set("PluralizeListTitles", PluralizeListTitles) } if hugoCmdV.PersistentFlags().Lookup("preserveTaxonomyNames").Changed { viper.Set("PreserveTaxonomyNames", PreserveTaxonomyNames) } if hugoCmdV.PersistentFlags().Lookup("editor").Changed { viper.Set("NewContentEditor", Editor) } if hugoCmdV.PersistentFlags().Lookup("logFile").Changed { viper.Set("LogFile", LogFile) } if BaseURL != "" { if !strings.HasSuffix(BaseURL, "/") { BaseURL = BaseURL + "/" } viper.Set("BaseURL", BaseURL) } if !viper.GetBool("RelativeURLs") && viper.GetString("BaseURL") == "" { jww.ERROR.Println("No 'baseurl' set in configuration or as a flag. Features like page menus will not work without one.") } if Theme != "" { viper.Set("theme", Theme) } if Destination != "" { viper.Set("PublishDir", Destination) } if Source != "" { viper.Set("WorkingDir", Source) } else { dir, _ := os.Getwd() viper.Set("WorkingDir", dir) } if hugoCmdV.PersistentFlags().Lookup("ignoreCache").Changed { viper.Set("IgnoreCache", IgnoreCache) } if CacheDir != "" { if helpers.FilePathSeparator != CacheDir[len(CacheDir)-1:] { CacheDir = CacheDir + helpers.FilePathSeparator } isDir, err := helpers.DirExists(CacheDir, hugofs.SourceFs) utils.CheckErr(err) if isDir == false { mkdir(CacheDir) } viper.Set("CacheDir", CacheDir) } else { viper.Set("CacheDir", helpers.GetTempDir("hugo_cache", hugofs.SourceFs)) } if VerboseLog || Logging || (viper.IsSet("LogFile") && viper.GetString("LogFile") != "") { if viper.IsSet("LogFile") && viper.GetString("LogFile") != "" { jww.SetLogFile(viper.GetString("LogFile")) } else { jww.UseTempLogFile("hugo") } } else { jww.DiscardLogging() } if viper.GetBool("verbose") { jww.SetStdoutThreshold(jww.LevelInfo) } if VerboseLog { jww.SetLogThreshold(jww.LevelInfo) } jww.INFO.Println("Using config file:", viper.ConfigFileUsed()) themeDir := helpers.GetThemeDir() if themeDir != "" { if _, err := os.Stat(themeDir); os.IsNotExist(err) { jww.FATAL.Fatalln("Unable to find theme Directory:", themeDir) } } themeVersionMismatch, minVersion := helpers.IsThemeVsHugoVersionMismatch() if themeVersionMismatch { jww.ERROR.Printf("Current theme does not support Hugo version %s. Minimum version required is %s\n", helpers.HugoReleaseVersion(), minVersion) } }
// InitializeConfig initializes a config file with sensible default configuration flags. func InitializeConfig() { viper.SetConfigFile(CfgFile) viper.AddConfigPath(Source) err := viper.ReadInConfig() if err != nil { jww.ERROR.Println("Unable to locate Config file. Perhaps you need to create a new site. Run `hugo help new` for details") } viper.RegisterAlias("indexes", "taxonomies") viper.SetDefault("Watch", false) viper.SetDefault("MetaDataFormat", "toml") viper.SetDefault("DisableRSS", false) viper.SetDefault("DisableSitemap", false) viper.SetDefault("ContentDir", "content") viper.SetDefault("LayoutDir", "layouts") viper.SetDefault("StaticDir", "static") viper.SetDefault("ArchetypeDir", "archetypes") viper.SetDefault("PublishDir", "public") viper.SetDefault("DataDir", "data") viper.SetDefault("DefaultLayout", "post") viper.SetDefault("BuildDrafts", false) viper.SetDefault("BuildFuture", false) viper.SetDefault("UglyURLs", false) viper.SetDefault("Verbose", false) viper.SetDefault("IgnoreCache", false) viper.SetDefault("CanonifyURLs", false) viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"}) viper.SetDefault("Permalinks", make(hugolib.PermalinkOverrides, 0)) viper.SetDefault("Sitemap", hugolib.Sitemap{Priority: -1}) viper.SetDefault("PygmentsStyle", "monokai") viper.SetDefault("DefaultExtension", "html") viper.SetDefault("PygmentsUseClasses", false) viper.SetDefault("DisableLiveReload", false) viper.SetDefault("PluralizeListTitles", true) viper.SetDefault("FootnoteAnchorPrefix", "") viper.SetDefault("FootnoteReturnLinkContents", "") viper.SetDefault("NewContentEditor", "") viper.SetDefault("Paginate", 10) viper.SetDefault("PaginatePath", "page") viper.SetDefault("Blackfriday", helpers.NewBlackfriday()) if hugoCmdV.PersistentFlags().Lookup("buildDrafts").Changed { viper.Set("BuildDrafts", Draft) } if hugoCmdV.PersistentFlags().Lookup("buildFuture").Changed { viper.Set("BuildFuture", Future) } if hugoCmdV.PersistentFlags().Lookup("uglyUrls").Changed { viper.Set("UglyURLs", UglyURLs) } if hugoCmdV.PersistentFlags().Lookup("disableRSS").Changed { viper.Set("DisableRSS", DisableRSS) } if hugoCmdV.PersistentFlags().Lookup("disableSitemap").Changed { viper.Set("DisableSitemap", DisableSitemap) } if hugoCmdV.PersistentFlags().Lookup("verbose").Changed { viper.Set("Verbose", Verbose) } if hugoCmdV.PersistentFlags().Lookup("pluralizeListTitles").Changed { viper.Set("PluralizeListTitles", PluralizeListTitles) } if hugoCmdV.PersistentFlags().Lookup("editor").Changed { viper.Set("NewContentEditor", Editor) } if hugoCmdV.PersistentFlags().Lookup("logFile").Changed { viper.Set("LogFile", LogFile) } if BaseURL != "" { if !strings.HasSuffix(BaseURL, "/") { BaseURL = BaseURL + "/" } viper.Set("BaseURL", BaseURL) } if viper.GetString("BaseURL") == "" { jww.ERROR.Println("No 'baseurl' set in configuration or as a flag. Features like page menus will not work without one.") } if Theme != "" { viper.Set("theme", Theme) } if Destination != "" { viper.Set("PublishDir", Destination) } if Source != "" { viper.Set("WorkingDir", Source) } else { dir, _ := os.Getwd() viper.Set("WorkingDir", dir) } if hugoCmdV.PersistentFlags().Lookup("ignoreCache").Changed { viper.Set("IgnoreCache", IgnoreCache) } if CacheDir != "" { if helpers.FilePathSeparator != CacheDir[len(CacheDir)-1:] { CacheDir = CacheDir + helpers.FilePathSeparator } isDir, err := helpers.DirExists(CacheDir, hugofs.SourceFs) utils.CheckErr(err) if isDir == false { mkdir(CacheDir) } viper.Set("CacheDir", CacheDir) } else { viper.Set("CacheDir", helpers.GetTempDir("hugo_cache", hugofs.SourceFs)) } if VerboseLog || Logging || (viper.IsSet("LogFile") && viper.GetString("LogFile") != "") { if viper.IsSet("LogFile") && viper.GetString("LogFile") != "" { jww.SetLogFile(viper.GetString("LogFile")) } else { jww.UseTempLogFile("hugo") } } else { jww.DiscardLogging() } if viper.GetBool("verbose") { jww.SetStdoutThreshold(jww.LevelInfo) } if VerboseLog { jww.SetLogThreshold(jww.LevelInfo) } jww.INFO.Println("Using config file:", viper.ConfigFileUsed()) }
// InitializeConfig initializes a config file with sensible default configuration flags. func InitializeConfig() { viper.SetConfigFile(CfgFile) viper.AddConfigPath(Source) err := viper.ReadInConfig() if err != nil { jww.ERROR.Println("Unable to locate Config file. Perhaps you need to create a new site. Run `hugo help new` for details") } viper.RegisterAlias("taxonomies", "indexes") viper.SetDefault("Watch", false) viper.SetDefault("MetaDataFormat", "toml") viper.SetDefault("DisableRSS", false) viper.SetDefault("DisableSitemap", false) viper.SetDefault("ContentDir", "content") viper.SetDefault("LayoutDir", "layouts") viper.SetDefault("StaticDir", "static") viper.SetDefault("ArchetypeDir", "archetypes") viper.SetDefault("PublishDir", "public") viper.SetDefault("DefaultLayout", "post") viper.SetDefault("BuildDrafts", false) viper.SetDefault("BuildFuture", false) viper.SetDefault("UglyUrls", false) viper.SetDefault("Verbose", false) viper.SetDefault("CanonifyUrls", false) viper.SetDefault("Indexes", map[string]string{"tag": "tags", "category": "categories"}) viper.SetDefault("Permalinks", make(hugolib.PermalinkOverrides, 0)) viper.SetDefault("Sitemap", hugolib.Sitemap{Priority: -1}) viper.SetDefault("PygmentsStyle", "monokai") viper.SetDefault("DefaultExtension", "html") viper.SetDefault("PygmentsUseClasses", false) viper.SetDefault("DisableLiveReload", false) viper.SetDefault("PluralizeListTitles", true) viper.SetDefault("FootnoteAnchorPrefix", "") viper.SetDefault("FootnoteReturnLinkContents", "") viper.SetDefault("NewContentEditor", "") viper.SetDefault("Paginate", 10) viper.SetDefault("PaginatePath", "page") viper.SetDefault("Blackfriday", new(helpers.Blackfriday)) if hugoCmdV.PersistentFlags().Lookup("buildDrafts").Changed { viper.Set("BuildDrafts", Draft) } if hugoCmdV.PersistentFlags().Lookup("buildFuture").Changed { viper.Set("BuildFuture", Future) } if hugoCmdV.PersistentFlags().Lookup("uglyUrls").Changed { viper.Set("UglyUrls", UglyUrls) } if hugoCmdV.PersistentFlags().Lookup("disableRSS").Changed { viper.Set("DisableRSS", DisableRSS) } if hugoCmdV.PersistentFlags().Lookup("disableSitemap").Changed { viper.Set("DisableSitemap", DisableSitemap) } if hugoCmdV.PersistentFlags().Lookup("verbose").Changed { viper.Set("Verbose", Verbose) } if hugoCmdV.PersistentFlags().Lookup("pluralizeListTitles").Changed { viper.Set("PluralizeListTitles", PluralizeListTitles) } if hugoCmdV.PersistentFlags().Lookup("editor").Changed { viper.Set("NewContentEditor", Editor) } if hugoCmdV.PersistentFlags().Lookup("logFile").Changed { viper.Set("LogFile", LogFile) } if BaseUrl != "" { if !strings.HasSuffix(BaseUrl, "/") { BaseUrl = BaseUrl + "/" } viper.Set("BaseUrl", BaseUrl) } if Theme != "" { viper.Set("theme", Theme) } if Destination != "" { viper.Set("PublishDir", Destination) } if Source != "" { viper.Set("WorkingDir", Source) } else { dir, _ := os.Getwd() viper.Set("WorkingDir", dir) } if VerboseLog || Logging || (viper.IsSet("LogFile") && viper.GetString("LogFile") != "") { if viper.IsSet("LogFile") && viper.GetString("LogFile") != "" { jww.SetLogFile(viper.GetString("LogFile")) } else { jww.UseTempLogFile("hugo") } } else { jww.DiscardLogging() } if viper.GetBool("verbose") { jww.SetStdoutThreshold(jww.LevelInfo) } if VerboseLog { jww.SetLogThreshold(jww.LevelInfo) } jww.INFO.Println("Using config file:", viper.ConfigFileUsed()) }
func InitializeConfig() { viper.SetConfigFile(CfgFile) viper.AddConfigPath(Source) err := viper.ReadInConfig() if err != nil { jww.ERROR.Println("Config not found... using only defaults, stuff may not work") } viper.RegisterAlias("taxonomies", "indexes") viper.SetDefault("Watch", false) viper.SetDefault("MetaDataFormat", "toml") viper.SetDefault("DisableRSS", false) viper.SetDefault("DisableSitemap", false) viper.SetDefault("ContentDir", "content") viper.SetDefault("LayoutDir", "layouts") viper.SetDefault("StaticDir", "static") viper.SetDefault("ArchetypeDir", "archetypes") viper.SetDefault("PublishDir", "public") viper.SetDefault("DefaultLayout", "post") viper.SetDefault("BuildDrafts", false) viper.SetDefault("BuildFuture", false) viper.SetDefault("UglyUrls", false) viper.SetDefault("Verbose", false) viper.SetDefault("CanonifyUrls", false) viper.SetDefault("Indexes", map[string]string{"tag": "tags", "category": "categories"}) viper.SetDefault("Permalinks", make(hugolib.PermalinkOverrides, 0)) viper.SetDefault("Sitemap", hugolib.Sitemap{Priority: -1}) viper.SetDefault("PygmentsStyle", "monokai") viper.SetDefault("PygmentsUseClasses", false) viper.SetDefault("DisableLiveReload", false) viper.SetDefault("PluralizeListTitles", true) if hugoCmdV.PersistentFlags().Lookup("buildDrafts").Changed { viper.Set("BuildDrafts", Draft) } if hugoCmdV.PersistentFlags().Lookup("buildFuture").Changed { viper.Set("BuildFuture", Future) } if hugoCmdV.PersistentFlags().Lookup("uglyUrls").Changed { viper.Set("UglyUrls", UglyUrls) } if hugoCmdV.PersistentFlags().Lookup("disableRSS").Changed { viper.Set("DisableRSS", DisableRSS) } if hugoCmdV.PersistentFlags().Lookup("disableSitemap").Changed { viper.Set("DisableSitemap", DisableSitemap) } if hugoCmdV.PersistentFlags().Lookup("verbose").Changed { viper.Set("Verbose", Verbose) } if hugoCmdV.PersistentFlags().Lookup("pluralizeListTitles").Changed { viper.Set("PluralizeListTitles", PluralizeListTitles) } if hugoCmdV.PersistentFlags().Lookup("logFile").Changed { viper.Set("LogFile", LogFile) } if BaseUrl != "" { if !strings.HasSuffix(BaseUrl, "/") { BaseUrl = BaseUrl + "/" } viper.Set("BaseUrl", BaseUrl) } if Theme != "" { viper.Set("theme", Theme) } if Destination != "" { viper.Set("PublishDir", Destination) } if Source != "" { viper.Set("WorkingDir", Source) } else { dir, _ := helpers.FindCWD() viper.Set("WorkingDir", dir) } if VerboseLog || Logging || (viper.IsSet("LogFile") && viper.GetString("LogFile") != "") { if viper.IsSet("LogFile") && viper.GetString("LogFile") != "" { jww.SetLogFile(viper.GetString("LogFile")) } else { jww.UseTempLogFile("hugo") } } else { jww.DiscardLogging() } if viper.GetBool("verbose") { jww.SetStdoutThreshold(jww.LevelInfo) } if VerboseLog { jww.SetLogThreshold(jww.LevelInfo) } jww.INFO.Println("Using config file:", viper.ConfigFileUsed()) }
// Main runs Centrifugo as a service. func Main() { var port string var address string var debug bool var name string var web string var engn string var logLevel string var logFile string var insecure bool var useSSL bool var sslCert string var sslKey string var redisHost string var redisPort string var redisPassword string var redisDB string var redisURL string var redisAPI bool var redisPool int var rootCmd = &cobra.Command{ Use: "", Short: "Centrifugo", Long: "Centrifuge + GO = Centrifugo – harder, better, faster, stronger", Run: func(cmd *cobra.Command, args []string) { viper.SetDefault("gomaxprocs", 0) viper.SetDefault("prefix", "") viper.SetDefault("web_password", "") viper.SetDefault("web_secret", "") viper.RegisterAlias("cookie_secret", "web_secret") viper.SetDefault("max_channel_length", 255) viper.SetDefault("channel_prefix", "centrifugo") viper.SetDefault("node_ping_interval", 5) viper.SetDefault("message_send_timeout", 60) viper.SetDefault("expired_connection_close_delay", 10) viper.SetDefault("presence_ping_interval", 25) viper.SetDefault("presence_expire_interval", 60) viper.SetDefault("private_channel_prefix", "$") viper.SetDefault("namespace_channel_boundary", ":") viper.SetDefault("user_channel_boundary", "#") viper.SetDefault("user_channel_separator", ",") viper.SetDefault("client_channel_boundary", "&") viper.SetDefault("sockjs_url", "https://cdn.jsdelivr.net/sockjs/1.0/sockjs.min.js") viper.SetDefault("project_name", "") viper.SetDefault("project_secret", "") viper.SetDefault("project_connection_lifetime", false) viper.SetDefault("project_watch", false) viper.SetDefault("project_publish", false) viper.SetDefault("project_anonymous", false) viper.SetDefault("project_presence", false) viper.SetDefault("project_history_size", 0) viper.SetDefault("project_history_lifetime", 0) viper.SetDefault("project_namespaces", "") viper.SetEnvPrefix("centrifugo") viper.BindEnv("engine") viper.BindEnv("insecure") viper.BindEnv("web_password") viper.BindEnv("web_secret") viper.BindEnv("project_name") viper.BindEnv("project_secret") viper.BindEnv("project_connection_lifetime") viper.BindEnv("project_watch") viper.BindEnv("project_publish") viper.BindEnv("project_anonymous") viper.BindEnv("project_join_leave") viper.BindEnv("project_presence") viper.BindEnv("project_history_size") viper.BindEnv("project_history_lifetime") viper.BindPFlag("port", cmd.Flags().Lookup("port")) viper.BindPFlag("address", cmd.Flags().Lookup("address")) viper.BindPFlag("debug", cmd.Flags().Lookup("debug")) viper.BindPFlag("name", cmd.Flags().Lookup("name")) viper.BindPFlag("web", cmd.Flags().Lookup("web")) viper.BindPFlag("engine", cmd.Flags().Lookup("engine")) viper.BindPFlag("insecure", cmd.Flags().Lookup("insecure")) viper.BindPFlag("ssl", cmd.Flags().Lookup("ssl")) viper.BindPFlag("ssl_cert", cmd.Flags().Lookup("ssl_cert")) viper.BindPFlag("ssl_key", cmd.Flags().Lookup("ssl_key")) viper.BindPFlag("log_level", cmd.Flags().Lookup("log_level")) viper.BindPFlag("log_file", cmd.Flags().Lookup("log_file")) viper.BindPFlag("redis_host", cmd.Flags().Lookup("redis_host")) viper.BindPFlag("redis_port", cmd.Flags().Lookup("redis_port")) viper.BindPFlag("redis_password", cmd.Flags().Lookup("redis_password")) viper.BindPFlag("redis_db", cmd.Flags().Lookup("redis_db")) viper.BindPFlag("redis_url", cmd.Flags().Lookup("redis_url")) viper.BindPFlag("redis_api", cmd.Flags().Lookup("redis_api")) viper.BindPFlag("redis_pool", cmd.Flags().Lookup("redis_pool")) err := validateConfig(configFile) if err != nil { logger.FATAL.Fatalln(err) } viper.SetConfigFile(configFile) err = viper.ReadInConfig() if err != nil { logger.FATAL.Fatalln("unable to locate config file") } setupLogging() if os.Getenv("GOMAXPROCS") == "" { if viper.IsSet("gomaxprocs") && viper.GetInt("gomaxprocs") > 0 { runtime.GOMAXPROCS(viper.GetInt("gomaxprocs")) } else { runtime.GOMAXPROCS(runtime.NumCPU()) } } logger.INFO.Println("GOMAXPROCS set to", runtime.GOMAXPROCS(0)) logger.INFO.Println("using config file:", viper.ConfigFileUsed()) c := newConfig() s := structureFromConfig(nil) app, err := libcentrifugo.NewApplication(c) if err != nil { logger.FATAL.Fatalln(err) } app.SetStructure(s) var e libcentrifugo.Engine switch viper.GetString("engine") { case "memory": e = libcentrifugo.NewMemoryEngine(app) case "redis": e = libcentrifugo.NewRedisEngine( app, viper.GetString("redis_host"), viper.GetString("redis_port"), viper.GetString("redis_password"), viper.GetString("redis_db"), viper.GetString("redis_url"), viper.GetBool("redis_api"), viper.GetInt("redis_pool"), ) default: logger.FATAL.Fatalln("unknown engine: " + viper.GetString("engine")) } logger.INFO.Println("engine:", viper.GetString("engine")) logger.DEBUG.Printf("%v\n", viper.AllSettings()) logger.INFO.Println("Use SSL:", viper.GetBool("ssl")) if viper.GetBool("ssl") { if viper.GetString("ssl_cert") == "" { logger.FATAL.Println("No SSL certificate provided") os.Exit(1) } if viper.GetString("ssl_key") == "" { logger.FATAL.Println("No SSL certificate key provided") os.Exit(1) } } app.SetEngine(e) app.Run() go handleSignals(app) mux := libcentrifugo.DefaultMux(app, viper.GetString("prefix"), viper.GetString("web"), viper.GetString("sockjs_url")) addr := viper.GetString("address") + ":" + viper.GetString("port") logger.INFO.Printf("start serving on %s\n", addr) if useSSL { if err := http.ListenAndServeTLS(addr, sslCert, sslKey, mux); err != nil { logger.FATAL.Fatalln("ListenAndServe:", err) } } else { if err := http.ListenAndServe(addr, mux); err != nil { logger.FATAL.Fatalln("ListenAndServe:", err) } } }, } rootCmd.Flags().StringVarP(&port, "port", "p", "8000", "port to bind to") rootCmd.Flags().StringVarP(&address, "address", "a", "", "address to listen on") rootCmd.Flags().BoolVarP(&debug, "debug", "d", false, "debug mode - please, do not use it in production") rootCmd.Flags().StringVarP(&configFile, "config", "c", "config.json", "path to config file") rootCmd.Flags().StringVarP(&name, "name", "n", "", "unique node name") rootCmd.Flags().StringVarP(&web, "web", "w", "", "optional path to web interface application") rootCmd.Flags().StringVarP(&engn, "engine", "e", "memory", "engine to use: memory or redis") rootCmd.Flags().BoolVarP(&insecure, "insecure", "", false, "start in insecure mode") rootCmd.Flags().BoolVarP(&useSSL, "ssl", "", false, "accept SSL connections. This requires an X509 certificate and a key file") rootCmd.Flags().StringVarP(&sslCert, "ssl_cert", "", "", "path to an X509 certificate file") rootCmd.Flags().StringVarP(&sslKey, "ssl_key", "", "", "path to an X509 certificate key") rootCmd.Flags().StringVarP(&logLevel, "log_level", "", "info", "set the log level: debug, info, error, critical, fatal or none") rootCmd.Flags().StringVarP(&logFile, "log_file", "", "", "optional log file - if not specified all logs go to STDOUT") rootCmd.Flags().StringVarP(&redisHost, "redis_host", "", "127.0.0.1", "redis host (Redis engine)") rootCmd.Flags().StringVarP(&redisPort, "redis_port", "", "6379", "redis port (Redis engine)") rootCmd.Flags().StringVarP(&redisPassword, "redis_password", "", "", "redis auth password (Redis engine)") rootCmd.Flags().StringVarP(&redisDB, "redis_db", "", "0", "redis database (Redis engine)") rootCmd.Flags().StringVarP(&redisURL, "redis_url", "", "", "redis connection URL (Redis engine)") rootCmd.Flags().BoolVarP(&redisAPI, "redis_api", "", false, "enable Redis API listener (Redis engine)") rootCmd.Flags().IntVarP(&redisPool, "redis_pool", "", 256, "Redis pool size (Redis engine)") var versionCmd = &cobra.Command{ Use: "version", Short: "Centrifugo version number", Long: `Print the version number of Centrifugo`, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Centrifugo v%s\n", VERSION) }, } var checkConfigFile string var checkConfigCmd = &cobra.Command{ Use: "checkconfig", Short: "Check configuration file", Long: `Check Centrifugo configuration file`, Run: func(cmd *cobra.Command, args []string) { err := validateConfig(checkConfigFile) if err != nil { logger.FATAL.Fatalln(err) } }, } checkConfigCmd.Flags().StringVarP(&checkConfigFile, "config", "c", "config.json", "path to config file to check") var outputConfigFile string var generateConfigCmd = &cobra.Command{ Use: "genconfig", Short: "Generate simple configuration file to start with", Long: `Generate simple configuration file to start with`, Run: func(cmd *cobra.Command, args []string) { err := generateConfig(outputConfigFile) if err != nil { logger.FATAL.Fatalln(err) } }, } generateConfigCmd.Flags().StringVarP(&outputConfigFile, "config", "c", "config.json", "path to output config file") rootCmd.AddCommand(versionCmd) rootCmd.AddCommand(checkConfigCmd) rootCmd.AddCommand(generateConfigCmd) rootCmd.Execute() }