ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 功能介绍 1 设置默认值 2 从json toml hcl 读取配置 3 从环境变量env 读取值 4 读缓冲区 5 远程读取配置文件 6 key不区分大小写 ## cobra配置viper cobra使用viper来加载配置 ``` func initConfig() { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } // Search config in home directory with name ".demo" (without extension). viper.AddConfigPath(home) // 当前目录下寻找配置文件 viper.AddConfigPath(".") viper.SetConfigName(".demo") } viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) // Unmarshal 将配置文件转成对象 cfgErr = viper.Unmarshal(&cfg) } } ``` 使用配置启动程序: ``` var testCmd = &cobra.Command{ Use: "test", Short: "A brief description of your command", Long: `what`, Run: serve, } func init() { RootCmd.AddCommand(testCmd) } func serve(cmd *cobra.Command, args []string) { if cfgErr != nil { fmt.Println(fmt.Errorf("Config error: %s", cfgErr)) return } demo.Run(&cfg) } ```