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

Golang toml.Decode函数代码示例

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

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



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

示例1: NewConfigFile

func NewConfigFile() (*ConfigFile, error) {
	source, err := ioutil.ReadFile(CLIConfig.ConfigFileLocation)

	if err != nil {
		if CLIConfig.IsPiping || CLIConfig.IsNotifying {
			return &ConfigFile{
				Data:      DataConfig{},
				Graphite:  GraphiteConfig{},
				JobsField: []Job{},
			}, nil
		}

		return nil, errors.New(fmt.Sprintf("Unable to open configuration file at %s. Did you use --config to specify the right path?\n\n", CLIConfig.ConfigFileLocation))
	}

	result := &ConfigFile{}

	_, err = toml.Decode(string(source), result)

	for _, job := range result.FlowField {
		result.JobsField = append(result.JobsField, job)
	}

	return result, err
}
开发者ID:nagyistge,项目名称:gotelemetry_agent,代码行数:25,代码来源:config_file.go


示例2: Export

// Retuns the configuration data into a generic object for for us.
func (cr *ConfigReader) Export() (interface{}, error) {
	var config interface{}
	buf := new(bytes.Buffer)
	buf.ReadFrom(cr.reader)

	switch cr.Format {
	case "yaml":
		if err := yaml.Unmarshal(buf.Bytes(), &config); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}

	case "json":
		if err := json.Unmarshal(buf.Bytes(), &config); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}

	case "toml":
		if _, err := toml.Decode(buf.String(), &config); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}
	default:
		return nil, err.UnsupportedConfigError(cr.Format)
	}

	return config, nil
}
开发者ID:markgustetic,项目名称:confer,代码行数:27,代码来源:configreader.go


示例3: main

func main() {
	configFile := flag.String("config", "benchmark_config.sample.toml", "Config file")

	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()

	data, err := ioutil.ReadFile(*configFile)
	if err != nil {
		panic(err)
	}
	var conf benchmarkConfig
	if _, err := toml.Decode(string(data), &conf); err != nil {
		panic(err)
	}
	logFile, err := os.OpenFile(conf.LogFile, os.O_RDWR|os.O_CREATE, 0660)
	if err != nil {
		panic(fmt.Sprintf("Error opening log file \"%s\": %s", conf.LogFile, err))
	}
	conf.Log = logFile
	defer logFile.Close()
	fmt.Println("Logging benchmark results to ", conf.LogFile)
	logFile.WriteString("Starting benchmark run...\n")

	harness := NewBenchmarkHarness(&conf)

	startTime := time.Now()
	harness.Run()
	elapsed := time.Now().Sub(startTime)

	message := fmt.Sprintf("Finished in %.3f seconds\n", elapsed.Seconds())
	fmt.Printf(message)
	logFile.WriteString(message)
}
开发者ID:hanshenu,项目名称:influxdb,代码行数:33,代码来源:influxdb_benchmark.go


示例4: ParseDbConfig

func ParseDbConfig(path string) (*DbConfig, error) {
	conf := &DbConfig{}
	content, err := ioutil.ReadFile(path + "/config.toml")
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Error while reading config.toml configuration: %v", err))
	}
	_, err = toml.Decode(string(content), &conf)
	if err != nil {
		return nil, err
	}
	if conf.User == "" {
		conf.User = "postgres"
	}
	if conf.Host == "" {
		conf.Host = "127.0.0.1"
	}
	if conf.Port == 0 {
		conf.Port = 5432
	}
	if conf.SslMode == "" {
		conf.SslMode = "disable"
	}
	return conf, nil

}
开发者ID:gophergala2016,项目名称:dbservice,代码行数:25,代码来源:parser.go


示例5: TestConfig_Parse

func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c httpd.Config
	if _, err := toml.Decode(`
enabled = true
bind-address = ":8080"
auth-enabled = true
log-enabled = true
write-tracing = true
pprof-enabled = true
https-enabled = true
https-certificate = "/dev/null"
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	} else if c.BindAddress != ":8080" {
		t.Fatalf("unexpected bind address: %s", c.BindAddress)
	} else if c.AuthEnabled != true {
		t.Fatalf("unexpected auth enabled: %v", c.AuthEnabled)
	} else if c.LogEnabled != true {
		t.Fatalf("unexpected log enabled: %v", c.LogEnabled)
	} else if c.WriteTracing != true {
		t.Fatalf("unexpected write tracing: %v", c.WriteTracing)
	} else if c.PprofEnabled != true {
		t.Fatalf("unexpected pprof enabled: %v", c.PprofEnabled)
	} else if c.HTTPSEnabled != true {
		t.Fatalf("unexpected https enabled: %v", c.HTTPSEnabled)
	} else if c.HTTPSCertificate != "/dev/null" {
		t.Fatalf("unexpected https certificate: %v", c.HTTPSCertificate)
	}
}
开发者ID:seiflotfy,项目名称:influxdb,代码行数:35,代码来源:config_test.go


示例6: TestConfig_Parse

func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c httpd.Config
	if _, err := toml.Decode(`
enabled = true
bind-address = ":8080"
auth-enabled = true
log-enabled = true
write-tracing = true
pprof-enabled = true
max-connections = 5000
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	} else if c.BindAddress != ":8080" {
		t.Fatalf("unexpected bind address: %s", c.BindAddress)
	} else if c.AuthEnabled != true {
		t.Fatalf("unexpected auth enabled: %v", c.AuthEnabled)
	} else if c.LogEnabled != true {
		t.Fatalf("unexpected log enabled: %v", c.LogEnabled)
	} else if c.WriteTracing != true {
		t.Fatalf("unexpected write tracing: %v", c.WriteTracing)
	} else if c.PprofEnabled != true {
		t.Fatalf("unexpected pprof enabled: %v", c.PprofEnabled)
	} else if c.MaxConnections != 5000 {
		t.Fatalf("unexpected max connections: %v", c.MaxConnections)
	}
}
开发者ID:messagedb,项目名称:messagedb,代码行数:32,代码来源:config_test.go


示例7: handleTomlMetaData

func (page *Page) handleTomlMetaData(datum []byte) (interface{}, error) {
	m := map[string]interface{}{}
	if _, err := toml.Decode(string(datum), &m); err != nil {
		return m, fmt.Errorf("Invalid TOML in %s \nError parsing page meta data: %s", page.FileName, err)
	}
	return m, nil
}
开发者ID:hugoduncan,项目名称:hugo,代码行数:7,代码来源:page.go


示例8: NewConfig

// NewConfig reads configuration from path. The format is deductted from file extension
//	* .json    - is decoded as json
//	* .yml     - is decoded as yaml
//	* .toml    - is decoded as toml
func NewConfig(path string) (*Config, error) {
	_, err := os.Stat(path)
	if err != nil {
		return nil, err
	}

	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	cfg := &Config{}
	switch filepath.Ext(path) {
	case ".json":
		jerr := json.Unmarshal(data, cfg)
		if jerr != nil {
			return nil, jerr
		}
	case ".toml":
		_, terr := toml.Decode(string(data), cfg)
		if terr != nil {
			return nil, terr
		}
	case ".yml":
		yerr := yaml.Unmarshal(data, cfg)
		if yerr != nil {
			return nil, yerr
		}

	default:
		return nil, errors.New("utron: config file not supported")
	}
	return cfg, nil
}
开发者ID:antonsofyan,项目名称:utron,代码行数:38,代码来源:config.go


示例9: FromToml

// 解析toml字符串
func (config *Configuration) FromToml(data string) error {
	config.mutex.Lock()
	defer config.mutex.Unlock()

	_, err := toml.Decode(data, &config.parameters)
	return err
}
开发者ID:doublemo,项目名称:infinity,代码行数:8,代码来源:config.go


示例10: parseTomlConfiguration

func parseTomlConfiguration(filename string) (*Configuration, error) {
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	tomlConfiguration := &TomlConfiguration{}
	_, err = toml.Decode(string(body), tomlConfiguration)
	if err != nil {
		return nil, err
	}

	config := &Configuration{
		AdminHttpPort:  tomlConfiguration.Admin.Port,
		AdminAssetsDir: tomlConfiguration.Admin.Assets,
		ApiHttpPort:    tomlConfiguration.Api.Port,
		RaftServerPort: tomlConfiguration.Raft.Port,
		RaftDir:        tomlConfiguration.Raft.Dir,
		ProtobufPort:   tomlConfiguration.Cluster.ProtobufPort,
		SeedServers:    tomlConfiguration.Cluster.SeedServers,
		DataDir:        tomlConfiguration.Storage.Dir,
		LogFile:        tomlConfiguration.Logging.File,
		LogLevel:       tomlConfiguration.Logging.Level,
		Hostname:       tomlConfiguration.Hostname,
	}

	return config, nil
}
开发者ID:schmurfy,项目名称:influxdb,代码行数:27,代码来源:configuration.go


示例11: TestConfig_Parse

func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c opentsdb.Config
	if _, err := toml.Decode(`
enabled = true
bind-address = ":9000"
database = "xxx"
consistency-level ="all"
tls-enabled = true
certificate = "/etc/ssl/cert.pem"
log-point-errors = true
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	} else if c.BindAddress != ":9000" {
		t.Fatalf("unexpected bind address: %s", c.BindAddress)
	} else if c.Database != "xxx" {
		t.Fatalf("unexpected database: %s", c.Database)
	} else if c.ConsistencyLevel != "all" {
		t.Fatalf("unexpected consistency-level: %s", c.ConsistencyLevel)
	} else if c.TLSEnabled != true {
		t.Fatalf("unexpected tls-enabled: %v", c.TLSEnabled)
	} else if c.Certificate != "/etc/ssl/cert.pem" {
		t.Fatalf("unexpected certificate: %s", c.Certificate)
	} else if !c.LogPointErrors {
		t.Fatalf("unexpected log-point-errors: %v", c.LogPointErrors)
	}
}
开发者ID:ChenXiukun,项目名称:influxdb,代码行数:32,代码来源:config_test.go


示例12: TestConfig_Parse_EnvOverride

// Ensure the configuration can be parsed.
func TestConfig_Parse_EnvOverride(t *testing.T) {
	// Parse configuration.
	var c run.Config
	if _, err := toml.Decode(`
[replay]
dir = "/tmp/replay"

[task]
dir = "/tmp/task"
`, &c); err != nil {
		t.Fatal(err)
	}

	if err := os.Setenv("KAPACITOR_REPLAY_DIR", "/var/lib/kapacitor/replay"); err != nil {
		t.Fatalf("failed to set env var: %v", err)
	}

	if err := os.Setenv("KAPACITOR_TASK_DIR", "/var/lib/kapacitor/task"); err != nil {
		t.Fatalf("failed to set env var: %v", err)
	}

	if err := c.ApplyEnvOverrides(); err != nil {
		t.Fatalf("failed to apply env overrides: %v", err)
	}

	// Validate configuration.
	if c.Replay.Dir != "/var/lib/kapacitor/replay" {
		t.Fatalf("unexpected replay dir: %s", c.Replay.Dir)
	} else if c.Task.Dir != "/var/lib/kapacitor/task" {
		t.Fatalf("unexpected task dir: %s", c.Task.Dir)
	}
}
开发者ID:md14454,项目名称:kapacitor,代码行数:33,代码来源:config_test.go


示例13: LoadConfig

// LoadConfig initializes the confd configuration by first setting defaults,
// then overriding setting from the confd config file, and finally overriding
// settings from flags set on the command line.
// It returns an error if any.
func LoadConfig(path string) error {
	setDefaults()
	if path == "" {
		log.Warning("Skipping confd config file.")
	} else {
		log.Debug("Loading " + path)

		configBytes, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}

		_, err = toml.Decode(string(configBytes), &config)
		if err != nil {
			return err
		}
	}
	processFlags()
	if !isValidateEtcdScheme(config.Confd.EtcdScheme) {
		return errors.New("Invalid etcd scheme: " + config.Confd.EtcdScheme)
	}
	err := setEtcdHosts()
	if err != nil {
		return err
	}
	return nil
}
开发者ID:nomyself,项目名称:confd,代码行数:31,代码来源:config.go


示例14: ParseConfig

// ParseConfig parses a configuration string into a config object.
func ParseConfig(s string) (*Config, error) {
	c := NewConfig()
	if _, err := toml.Decode(s, &c); err != nil {
		return nil, err
	}
	return c, nil
}
开发者ID:yinlei,项目名称:influxdb,代码行数:8,代码来源:config.go


示例15: getConfiguration

func (p *BaseProvider) getConfiguration(defaultTemplateFile string, funcMap template.FuncMap, templateObjects interface{}) (*types.Configuration, error) {
	var (
		buf []byte
		err error
	)
	configuration := new(types.Configuration)
	tmpl := template.New(p.Filename).Funcs(funcMap)
	if len(p.Filename) > 0 {
		buf, err = ioutil.ReadFile(p.Filename)
		if err != nil {
			return nil, err
		}
	} else {
		buf, err = autogen.Asset(defaultTemplateFile)
		if err != nil {
			return nil, err
		}
	}
	_, err = tmpl.Parse(string(buf))
	if err != nil {
		return nil, err
	}

	var buffer bytes.Buffer
	err = tmpl.Execute(&buffer, templateObjects)
	if err != nil {
		return nil, err
	}

	if _, err := toml.Decode(buffer.String(), configuration); err != nil {
		return nil, err
	}
	return configuration, nil
}
开发者ID:octoblu,项目名称:traefik,代码行数:34,代码来源:provider.go


示例16: main

func main() {
	usage := `goclitool.

Usage:
  goclitool [-c <configfile>]
  goclitool -h
  goclitool -v

Options:
  -c --config=<configfile>    Path to goclitool config file [default: config.toml].
  -h --help                   Show this help message.
  -v --version                Show version.`

	args, err := docopt.Parse(usage, nil, true, "goclitool 0.0", false)
	if err != nil {
		log.Fatal("Error parsing usage string: " + err.Error())
	}
	conffile, err := ioutil.ReadFile(args["--config"].(string))
	if err != nil {
		log.Fatal("Error readin config file: " + err.Error())
	}
	var conf Config
	if _, err := toml.Decode(string(conffile), &conf); err != nil {
		log.Fatal("Error decoding toml config" + err.Error())
	}
}
开发者ID:wlcx,项目名称:go-cli-template,代码行数:26,代码来源:main.go


示例17: LoadCmdConfig

func LoadCmdConfig(configFileName string) (config map[string]toml.Primitive, md *toml.MetaData, err error) {
	exePath, err1 := exec.LookPath(os.Args[0])
	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	exeFullPath, err1 := filepath.Abs(exePath)
	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	configFullPath := fmt.Sprintf("%s/%s", filepath.Dir(exeFullPath), configFileName)

	file, err1 := os.Open(configFullPath)
	defer file.Close()

	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	data, err1 := ioutil.ReadAll(file)
	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	config = make(map[string]toml.Primitive)
	md1, err1 := toml.Decode(string(data), config)
	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	md = &md1
	return config, md, nil
}
开发者ID:cxwshawn,项目名称:ornet,代码行数:34,代码来源:srv_conf.go


示例18: TestConfig_Parse

func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c continuous_querier.Config
	if _, err := toml.Decode(`
recompute-previous-n = 1
recompute-no-older-than = "10s"
compute-runs-per-interval = 2
compute-no-more-than = "20s"
enabled = true
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.RecomputePreviousN != 1 {
		t.Fatalf("unexpected recompute previous n: %d", c.RecomputePreviousN)
	} else if time.Duration(c.RecomputeNoOlderThan) != 10*time.Second {
		t.Fatalf("unexpected recompute no older than: %v", c.RecomputeNoOlderThan)
	} else if c.ComputeRunsPerInterval != 2 {
		t.Fatalf("unexpected compute runs per interval: %d", c.ComputeRunsPerInterval)
	} else if time.Duration(c.ComputeNoMoreThan) != 20*time.Second {
		t.Fatalf("unexpected compute no more than: %v", c.ComputeNoMoreThan)
	} else if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	}
}
开发者ID:jportoles,项目名称:influxdb092,代码行数:26,代码来源:config_test.go


示例19: init

func init() {
	currDir, e1 := os.Getwd()
	gjoa.Fatal(e1)
	propPath := currDir
	u, e2 := osuser.Current()
	if e2 == nil {
		propPath = filepath.Join(u.HomeDir, ".config", "gjoa")
	}
	propPath = filepath.Join(propPath, "properties.toml")
	propEnvVar := os.Getenv("GJOA_PROPERTIES")
	if len(propEnvVar) > 0 {
		propPath = propEnvVar
	}

	// Read toml config file from configPath.
	dat, e3 := ioutil.ReadFile(propPath)
	if e3 == nil {
		_, e4 := toml.Decode(string(dat), config)
		gjoa.Fatal(e4)
	} else {
		props = new(Properties)
		glog.V(2).Infof("unable to read properties file - ", e3)
	}
	defaultLogDir := filepath.Join(currDir, "log")
	if len(props.LogDir) > 0 {
		defaultLogDir = props.LogDir
	}
	logDir = app.Flag("log", "Log output dir.").Default(defaultLogDir).String()
}
开发者ID:henrylee2cn,项目名称:gjoa,代码行数:29,代码来源:gjoa.go


示例20: TestConfig_Parse

func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c udp.Config
	if _, err := toml.Decode(`
enabled = true
bind-address = ":4444"
database = "awesomedb"
retention-policy = "awesomerp"
batch-size = 100
batch-pending = 9
batch-timeout = "10ms"
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	} else if c.BindAddress != ":4444" {
		t.Fatalf("unexpected bind address: %s", c.BindAddress)
	} else if c.Database != "awesomedb" {
		t.Fatalf("unexpected database: %s", c.Database)
	} else if c.RetentionPolicy != "awesomerp" {
		t.Fatalf("unexpected retention policy: %s", c.RetentionPolicy)
	} else if c.BatchSize != 100 {
		t.Fatalf("unexpected batch size: %d", c.BatchSize)
	} else if c.BatchPending != 9 {
		t.Fatalf("unexpected batch pending: %d", c.BatchPending)
	} else if time.Duration(c.BatchTimeout) != (10 * time.Millisecond) {
		t.Fatalf("unexpected batch timeout: %v", c.BatchTimeout)
	}
}
开发者ID:nickrobinson,项目名称:influxdb,代码行数:32,代码来源:config_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang toml.DecodeFile函数代码示例发布时间:2022-05-24
下一篇:
Golang migration.LimitedTx类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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