• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang configor.Load函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/jinzhu/configor.Load函数的典型用法代码示例。如果您正苦于以下问题:Golang Load函数的具体用法?Golang Load怎么用?Golang Load使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Load函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: getConfig

// Loading configuration from yaml file
func getConfig(c *cli.Context) (config.Config, error) {
	yamlPath := c.GlobalString("config")
	conf := config.Config{}

	err := configor.Load(&conf, yamlPath)
	return conf, err
}
开发者ID:grengojbo,项目名称:ads,代码行数:8,代码来源:commands.go


示例2: TestLoadConfigurationByEnvironment

func TestLoadConfigurationByEnvironment(t *testing.T) {
	config := generateDefaultConfig()
	config2 := struct {
		APPName string
	}{
		APPName: "config2",
	}

	if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
		defer file.Close()
		defer os.Remove(file.Name())
		configBytes, _ := yaml.Marshal(config)
		config2Bytes, _ := yaml.Marshal(config2)
		ioutil.WriteFile(file.Name()+".yaml", configBytes, 0644)
		defer os.Remove(file.Name() + ".yaml")
		ioutil.WriteFile(file.Name()+".production.yaml", config2Bytes, 0644)
		defer os.Remove(file.Name() + ".production.yaml")

		var result Config
		os.Setenv("CONFIGOR_ENV", "production")
		defer os.Setenv("CONFIGOR_ENV", "")
		if err := configor.Load(&result, file.Name()+".yaml"); err != nil {
			t.Errorf("No error should happen when load configurations, but got %v", err)
		}

		var defaultConfig = generateDefaultConfig()
		defaultConfig.APPName = "config2"
		if !reflect.DeepEqual(result, defaultConfig) {
			t.Errorf("result should be load configurations by environment correctly")
		}
	}
}
开发者ID:jinzhu,项目名称:configor,代码行数:32,代码来源:configor_test.go


示例3: TestResetPrefixToBlank

func TestResetPrefixToBlank(t *testing.T) {
	config := generateDefaultConfig()

	if bytes, err := json.Marshal(config); err == nil {
		if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
			defer file.Close()
			defer os.Remove(file.Name())
			file.Write(bytes)
			var result Config
			os.Setenv("CONFIGOR_ENV_PREFIX", "-")
			os.Setenv("APPNAME", "config2")
			os.Setenv("DB_NAME", "db_name")
			defer os.Setenv("CONFIGOR_ENV_PREFIX", "")
			defer os.Setenv("APPNAME", "")
			defer os.Setenv("DB_NAME", "")
			configor.Load(&result, file.Name())

			var defaultConfig = generateDefaultConfig()
			defaultConfig.APPName = "config2"
			defaultConfig.DB.Name = "db_name"
			if !reflect.DeepEqual(result, defaultConfig) {
				t.Errorf("result should equal to original configuration")
			}
		}
	}
}
开发者ID:jinzhu,项目名称:configor,代码行数:26,代码来源:configor_test.go


示例4: init

func init() {
	if err := configor.Load(&Config, "config/database.yml", "config/smtp.yml"); err != nil {
		panic(err)
	}

	View = render.New()
}
开发者ID:grengojbo,项目名称:qor-example,代码行数:7,代码来源:config.go


示例5: main

func main() {
	filepaths, _ := filepath.Glob("db/seeds/data/*.yml")
	if err := configor.Load(&Seeds, filepaths...); err != nil {
		panic(err)
	}

	truncateTables()
	createRecords()
}
开发者ID:trigrass2,项目名称:qor-example,代码行数:9,代码来源:main.go


示例6: init

func init() {
	Fake, _ = faker.New("en")
	Fake.Rand = rand.New(rand.NewSource(42))
	rand.Seed(time.Now().UnixNano())

	filepaths, _ := filepath.Glob("db/seeds/data/*.yml")
	if err := configor.Load(&Seeds, filepaths...); err != nil {
		panic(err)
	}
}
开发者ID:caghan,项目名称:qor-example,代码行数:10,代码来源:seeds.go


示例7: init

func init() {
	if err := configor.Load(&Config, "config/database.yml", "config/smtp.yml"); err != nil {
		panic(err)
	}

	View = render.New()

	htmlSanitizer := bluemonday.UGCPolicy()
	View.RegisterFuncMap("raw", func(str string) template.HTML {
		return template.HTML(htmlSanitizer.Sanitize(str))
	})
}
开发者ID:qor,项目名称:qor-example,代码行数:12,代码来源:config.go


示例8: init

func init() {
	err := configor.Load(&config, "./config/verify_faces.json")
	if err != nil {
		myFatal("Read config file error: ", err)
	}

	for i, _ := range config.FaceRecServers {
		if len(config.FaceRecServers[i].Url) == 0 {
			config.FaceRecServers[i].Url = config.FaceRecServers[i].Host + ":" + config.FaceRecServers[i].Port
		}
	}
}
开发者ID:zalemwoo,项目名称:BDBKImageServer,代码行数:12,代码来源:verify_faces.go


示例9: TestLoadNormalConfig

func TestLoadNormalConfig(t *testing.T) {
	config := generateDefaultConfig()
	if bytes, err := json.Marshal(config); err == nil {
		if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
			defer file.Close()
			file.Write(bytes)
			var result Config
			configor.Load(&result, file.Name())
			if !reflect.DeepEqual(result, config) {
				t.Errorf("result should equal to original configuration")
			}
		}
	} else {
		t.Errorf("failed to marshal config")
	}
}
开发者ID:47bytes,项目名称:configor,代码行数:16,代码来源:configor_test.go


示例10: TestMissingRequiredValue

func TestMissingRequiredValue(t *testing.T) {
	config := generateDefaultConfig()
	config.DB.Password = ""

	if bytes, err := json.Marshal(config); err == nil {
		if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
			defer file.Close()
			file.Write(bytes)
			var result Config
			if err := configor.Load(&result, file.Name()); err == nil {
				t.Errorf("Should got error when load configuration missing db password")
			}
		}
	} else {
		t.Errorf("failed to marshal config")
	}
}
开发者ID:47bytes,项目名称:configor,代码行数:17,代码来源:configor_test.go


示例11: TestLoadTOMLConfigWithTomlExtension

func TestLoadTOMLConfigWithTomlExtension(t *testing.T) {
	config := generateDefaultConfig()
	var buffer bytes.Buffer
	if err := toml.NewEncoder(&buffer).Encode(config); err == nil {
		if file, err := ioutil.TempFile("/tmp", "configor.toml"); err == nil {
			defer file.Close()
			defer os.Remove(file.Name())
			file.Write(buffer.Bytes())
			var result Config
			configor.Load(&result, file.Name())
			if !reflect.DeepEqual(result, config) {
				t.Errorf("result should equal to original configuration")
			}
		}
	} else {
		t.Errorf("failed to marshal config")
	}
}
开发者ID:jinzhu,项目名称:configor,代码行数:18,代码来源:configor_test.go


示例12: TestReadFromEnvironmentWithSpecifiedEnvName

func TestReadFromEnvironmentWithSpecifiedEnvName(t *testing.T) {
	config := generateDefaultConfig()

	if bytes, err := json.Marshal(config); err == nil {
		if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
			defer file.Close()
			file.Write(bytes)
			var result Config
			os.Setenv("DBPassword", "db_password")
			configor.Load(&result, file.Name())

			var defaultConfig = generateDefaultConfig()
			defaultConfig.DB.Password = "db_password"
			if !reflect.DeepEqual(result, defaultConfig) {
				t.Errorf("result should equal to original configuration")
			}
		}
	}
}
开发者ID:47bytes,项目名称:configor,代码行数:19,代码来源:configor_test.go


示例13: TestDefaultValue

func TestDefaultValue(t *testing.T) {
	config := generateDefaultConfig()
	config.APPName = ""
	config.DB.Port = 0

	if bytes, err := json.Marshal(config); err == nil {
		if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
			defer file.Close()
			file.Write(bytes)
			var result Config
			configor.Load(&result, file.Name())
			if !reflect.DeepEqual(result, generateDefaultConfig()) {
				t.Errorf("result should be set default value correctly")
			}
		}
	} else {
		t.Errorf("failed to marshal config")
	}
}
开发者ID:47bytes,项目名称:configor,代码行数:19,代码来源:configor_test.go


示例14: TestAnonymousStruct

func TestAnonymousStruct(t *testing.T) {
	config := generateDefaultConfig()

	if bytes, err := json.Marshal(config); err == nil {
		if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
			defer file.Close()
			defer os.Remove(file.Name())
			file.Write(bytes)
			var result Config
			os.Setenv("CONFIGOR_DESCRIPTION", "environment description")
			defer os.Setenv("CONFIGOR_DESCRIPTION", "")
			configor.Load(&result, file.Name())

			var defaultConfig = generateDefaultConfig()
			defaultConfig.Anonymous.Description = "environment description"
			if !reflect.DeepEqual(result, defaultConfig) {
				t.Errorf("result should equal to original configuration")
			}
		}
	}
}
开发者ID:jinzhu,项目名称:configor,代码行数:21,代码来源:configor_test.go


示例15: TestOverwriteConfigurationWithEnvironmentWithDefaultPrefix

func TestOverwriteConfigurationWithEnvironmentWithDefaultPrefix(t *testing.T) {
	config := generateDefaultConfig()

	if bytes, err := json.Marshal(config); err == nil {
		if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
			defer file.Close()
			file.Write(bytes)
			var result Config
			os.Setenv("CONFIGOR_APPNAME", "config2")
			os.Setenv("CONFIGOR_DB_NAME", "db_name")
			configor.Load(&result, file.Name())
			os.Setenv("CONFIGOR_APPNAME", "")
			os.Setenv("CONFIGOR_DB_NAME", "")

			var defaultConfig = generateDefaultConfig()
			defaultConfig.APPName = "config2"
			defaultConfig.DB.Name = "db_name"
			if !reflect.DeepEqual(result, defaultConfig) {
				t.Errorf("result should equal to original configuration")
			}
		}
	}
}
开发者ID:47bytes,项目名称:configor,代码行数:23,代码来源:configor_test.go


示例16: init

func init() {
	err := configor.Load(&config, "./config/server_config.json")
	if err != nil {
		myFatal("Read config file error: ", err)
	}
}
开发者ID:zalemwoo,项目名称:BDBKImageServer,代码行数:6,代码来源:server.go


示例17: init

func init() {
	if err := configor.Load(&Config, "config/database.yml"); err != nil {
		panic(err)
	}
}
开发者ID:rand99,项目名称:qor-example,代码行数:5,代码来源:config.go


示例18: readConfig

func readConfig(parse bool) {
	var err error
	// Set defaults
	ConfigYAML.UDPServiceAddress = defaultUDPServiceAddress
	ConfigYAML.TCPServiceAddress = defaultTCPServiceAddress
	ConfigYAML.MaxUDPPacketSize = maxUDPPacket
	ConfigYAML.BackendType = defaultBackendType
	ConfigYAML.PostFlushCmd = "stdout"
	ConfigYAML.GraphiteAddress = defaultGraphiteAddress
	ConfigYAML.OpenTSDBAddress = defaultOpenTSDBAddress
	ConfigYAML.FlushInterval = flushInterval
	ConfigYAML.LogLevel = "error"
	ConfigYAML.ShowVersion = false
	ConfigYAML.DeleteGauges = true
	ConfigYAML.ResetCounters = true
	ConfigYAML.PersistCountKeys = 0
	ConfigYAML.StatsPrefix = statsPrefixName
	ConfigYAML.StoreDb = dbPath
	ConfigYAML.Prefix = ""
	ConfigYAML.ExtraTags = ""
	ConfigYAML.PercentThreshold = Percentiles{}
	// Percentiles{{Float: 50.0, Str: "50"}, {Float: 80.0, Str: "80"}, {Float: 90.0, Str: "90"}, {Float: 95.0, Str: "95"}}
	ConfigYAML.PrintConfig = false
	ConfigYAML.LogName = "stdout"
	ConfigYAML.LogToSyslog = true
	ConfigYAML.SyslogUDPAddress = "localhost:514"

	Config = ConfigYAML

	os.Setenv("CONFIGOR_ENV_PREFIX", "SD")

	configFile = flag.String("config", "", "Configuration file name (warning not error if not exists). Standard: "+configPath)
	flag.StringVar(&Config.UDPServiceAddress, "udp-addr", ConfigYAML.UDPServiceAddress, "UDP listen service address")
	flag.StringVar(&Config.TCPServiceAddress, "tcp-addr", ConfigYAML.TCPServiceAddress, "TCP listen service address, if set")
	flag.Int64Var(&Config.MaxUDPPacketSize, "max-udp-packet-size", ConfigYAML.MaxUDPPacketSize, "Maximum UDP packet size")
	flag.StringVar(&Config.BackendType, "backend-type", ConfigYAML.BackendType, "MANDATORY: Backend to use: graphite, opentsdb, external, dummy")
	flag.StringVar(&Config.PostFlushCmd, "post-flush-cmd", ConfigYAML.PostFlushCmd, "Command to run on each flush")
	flag.StringVar(&Config.GraphiteAddress, "graphite", ConfigYAML.GraphiteAddress, "Graphite service address")
	flag.StringVar(&Config.OpenTSDBAddress, "opentsdb", ConfigYAML.OpenTSDBAddress, "OpenTSDB service address")
	flag.Int64Var(&Config.FlushInterval, "flush-interval", ConfigYAML.FlushInterval, "Flush interval (seconds)")
	flag.StringVar(&Config.LogLevel, "log-level", ConfigYAML.LogLevel, "Set log level (debug,info,warn,error,fatal)")
	flag.BoolVar(&Config.ShowVersion, "version", ConfigYAML.ShowVersion, "Print version string")
	flag.BoolVar(&Config.DeleteGauges, "delete-gauges", ConfigYAML.DeleteGauges, "Don't send values to graphite for inactive gauges, as opposed to sending the previous value")
	flag.BoolVar(&Config.ResetCounters, "reset-counters", ConfigYAML.ResetCounters, "Reset counters after sending value to backend (send rate) or  send cumulated value (artificial counter - eg. for OpenTSDB & Grafana)")
	flag.Int64Var(&Config.PersistCountKeys, "persist-count-keys", ConfigYAML.PersistCountKeys, "Number of flush-intervals to persist count keys")
	flag.StringVar(&Config.StatsPrefix, "stats-prefix", ConfigYAML.StatsPrefix, "Name for internal application metrics (no prefix prepended)")
	flag.StringVar(&Config.StoreDb, "store-db", ConfigYAML.StoreDb, "Name of database for permanent counters storage (for conversion from rate to counter)")
	flag.StringVar(&Config.Prefix, "prefix", ConfigYAML.Prefix, "Prefix for all stats")
	flag.StringVar(&Config.ExtraTags, "extra-tags", ConfigYAML.ExtraTags, "Default tags added to all measures in format: tag1=value1 tag2=value2")
	flag.Var(&Config.PercentThreshold, "percent-threshold", "Percentile calculation for timers (0-100, may be given multiple times)")
	flag.BoolVar(&Config.PrintConfig, "print-config", ConfigYAML.PrintConfig, "Print config in YAML format")
	flag.StringVar(&Config.LogName, "log-name", ConfigYAML.LogName, "Name of file to log into. If \"stdout\" than logs to stdout.If empty logs go to /dev/null")
	flag.BoolVar(&Config.LogToSyslog, "log-to-syslopg", ConfigYAML.LogToSyslog, "Log to syslog")
	flag.StringVar(&Config.SyslogUDPAddress, "syslog-udp-address", ConfigYAML.SyslogUDPAddress, "Syslog address with port number eg. localhost:514. If empty log to unix socket")
	if parse {
		flag.Parse()
	}

	if len(*configFile) > 0 {
		if _, err = os.Stat(*configFile); os.IsNotExist(err) {
			fmt.Printf("# Warning: No config file: %s\n", *configFile)
			*configFile = ""
		}

		if len(*configFile) > 0 {
			err = configor.Load(&ConfigYAML, *configFile)
			if err != nil {
				fmt.Printf("Error loading config file: %s\n", err)
			} else {
				// set configs read form YAML file

				// save 2 flags
				tmpConfig := Config
				// Overwites flags
				Config = ConfigYAML
				// restore 2 flags
				Config.ShowVersion = tmpConfig.ShowVersion
				Config.PrintConfig = tmpConfig.PrintConfig

			}
		}

		// visitor := func(a *flag.Flag) {
		// 	fmt.Println(">", a.Name, "value=", a.Value)
		// 	switch a.Name {
		// 	case "print-config", "version":
		// 		break
		// 	case "udp-addr":
		// 		ConfigYAML.UDPServiceAddress = a.Value.(string)
		// 	default:
		// 		fmt.Printf("Internal Config Error - unknown variable: %s\n", a.Name)
		// 		os.Exit(1)
		// 	}
		//
		// }
		// flag.Visit(visitor)
	}

	// Normalize prefix
	Config.Prefix = normalizeDot(Config.Prefix, true)
//.........这里部分代码省略.........
开发者ID:wojtekzw,项目名称:statsdaemon,代码行数:101,代码来源:statsdaemon.go


示例19: ConfigLoad

/*
ConfigLoad loads configuration settings from files and environment
variables. Note, this function exits on error, since without config we can't
do anything.

We prefer settings in config file in current dir (or the current dir's parent
dir if the useparentdir option is true (used for test scripts)) over config file
in home directory over config file in dir pointed to by WR_CONFIG_DIR.

The deployment argument determines if we read .wr_config.production.yml or
.wr_config.development.yml; we always read .wr_config.yml. If the empty
string is supplied, deployment is development if you're in the git repository
directory. Otherwise, deployment is taken from the environment variable
WR_DEPLOYMENT, and if that's not set it defaults to production.

Multiple of these files can be used to have settings that are common to
multiple users and deployments, and settings specific to users or deployments.

Settings found in no file can be set with the environment variable
WR_<setting name in caps>, eg.
export WR_MANAGER_PORT="11301"
*/
func ConfigLoad(deployment string, useparentdir bool) Config {
	pwd, err := os.Getwd()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	if useparentdir {
		pwd = filepath.Dir(pwd)
	}

	// if deployment not set on the command line
	if deployment != "development" && deployment != "production" {
		deployment = DefaultDeployment()
	}
	os.Setenv("CONFIGOR_ENV", deployment)
	os.Setenv("CONFIGOR_ENV_PREFIX", "WR")
	ConfigDeploymentBasename := ".wr_config." + deployment + ".yml"

	// read the config files. We have to check file existence before passing
	// these to configor.Load, or it will complain
	var configFiles []string
	configFile := filepath.Join(pwd, configCommonBasename)
	_, err = os.Stat(configFile)
	if _, err2 := os.Stat(filepath.Join(pwd, ConfigDeploymentBasename)); err == nil || err2 == nil {
		configFiles = append(configFiles, configFile)
	}
	home := os.Getenv("HOME")
	if home != "" {
		configFile = filepath.Join(home, configCommonBasename)
		_, err = os.Stat(configFile)
		if _, err2 := os.Stat(filepath.Join(home, ConfigDeploymentBasename)); err == nil || err2 == nil {
			configFiles = append(configFiles, configFile)
		}
	}
	if configDir := os.Getenv("WR_CONFIG_DIR"); configDir != "" {
		configFile = filepath.Join(configDir, configCommonBasename)
		_, err = os.Stat(configFile)
		if _, err2 := os.Stat(filepath.Join(configDir, ConfigDeploymentBasename)); err == nil || err2 == nil {
			configFiles = append(configFiles, configFile)
		}
	}

	config := Config{}
	configor.Load(&config, configFiles...)
	config.Deployment = deployment

	// convert the possible ~/ in Manager_dir to abs path to user's home
	if home != "" && strings.HasPrefix(config.ManagerDir, "~/") {
		mdir := strings.TrimLeft(config.ManagerDir, "~/")
		mdir = filepath.Join(home, mdir)
		config.ManagerDir = mdir
	}
	config.ManagerDir += "_" + deployment

	// create the manager dir now, or else we're doomed to failure
	err = os.MkdirAll(config.ManagerDir, 0700)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// convert the possible relative paths in Manager_*_file to abs paths in
	// Manager_dir
	if !filepath.IsAbs(config.ManagerPidFile) {
		config.ManagerPidFile = filepath.Join(config.ManagerDir, config.ManagerPidFile)
	}
	if !filepath.IsAbs(config.ManagerLogFile) {
		config.ManagerLogFile = filepath.Join(config.ManagerDir, config.ManagerLogFile)
	}
	if !filepath.IsAbs(config.ManagerDbFile) {
		config.ManagerDbFile = filepath.Join(config.ManagerDir, config.ManagerDbFile)
	}
	if !filepath.IsAbs(config.ManagerDbBkFile) {
		//*** we need to support this being on a different machine, possibly on an S3-style object store
		config.ManagerDbBkFile = filepath.Join(config.ManagerDir, config.ManagerDbBkFile)
	}

//.........这里部分代码省略.........
开发者ID:sb10,项目名称:vrpipe,代码行数:101,代码来源:config.go


示例20: main

func main() {
	configor.Load(&Config, "../config/config.json")
	fmt.Printf("config: %#v", Config.APPName)
}
开发者ID:Focinfi,项目名称:GolangPractices,代码行数:4,代码来源:learn_configor.go



注:本文中的github.com/jinzhu/configor.Load函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang gorm.Expr函数代码示例发布时间:2022-05-23
下一篇:
Golang cli.App类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap