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

Golang hcl.Decode函数代码示例

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

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



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

示例1: Parse

// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
	// Decode the rules
	p := &Policy{Raw: rules}
	if err := hcl.Decode(p, rules); err != nil {
		return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
	}

	// Validate the path policy
	for _, pp := range p.Paths {
		// Strip the glob character if found
		if strings.HasSuffix(pp.Prefix, "*") {
			pp.Prefix = strings.TrimSuffix(pp.Prefix, "*")
			pp.Glob = true
		}

		// Check the policy is valid
		switch pp.Policy {
		case PathPolicyDeny:
		case PathPolicyRead:
		case PathPolicyWrite:
		case PathPolicySudo:
		default:
			return nil, fmt.Errorf("Invalid path policy: %#v", pp)
		}
	}
	return p, nil
}
开发者ID:vincentaubert,项目名称:vault,代码行数:30,代码来源:policy.go


示例2: LoadServices

func LoadServices(root string) (d []Config, err error) {
	files, _ := filepath.Glob(root + "/*.hcl")
	for _, file := range files {
		data, err := readFile(file)
		if err != nil {
			return nil, err
		}

		var deploy ServiceFile
		err = hcl.Decode(&deploy, data)
		if err != nil {
			return nil, err
		}

		for i, service := range deploy.Services {
			for key, value := range service.RawArtifact {
				value["type"] = key
				deploy.Services[i].Artifact = value
			}
		}

		d = append(d, deploy.Services...)
	}
	return
}
开发者ID:ChrisMcKenzie,项目名称:dropship,代码行数:25,代码来源:service.go


示例3: applyConfigFile

func applyConfigFile(options *Options, filePath string) error {
	filePath = expandHomeDir(filePath)
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		return err
	}

	fileString := []byte{}
	log.Printf("Loading config file at: %s", filePath)
	fileString, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
	}

	config := make(map[string]interface{})
	hcl.Decode(&config, string(fileString))
	o := structs.New(options)
	for _, name := range o.Names() {
		configName := strings.ToLower(strings.Join(camelcase.Split(name), "_"))
		if val, ok := config[configName]; ok {
			field, ok := o.FieldOk(name)
			if !ok {
				return errors.New("No such field: " + name)
			}
			err := field.Set(val)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
开发者ID:nkiraly,项目名称:gotty,代码行数:32,代码来源:app.go


示例4: Load

//Load provides loading of configuration file
func Load(path string, item interface{}) error {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	switch checkPath(path) {
	case jsontype:
		err := json.Unmarshal([]byte(data), item)
		if err != nil {
			return err
		}

		return nil

	case yamltype:
		err := yaml.Unmarshal([]byte(data), item)
		if err != nil {
			return err
		}

		return nil

	case hcltype:
		err := hcl.Decode(item, string(data))
		if err != nil {
			return err
		}

		return nil
	default:
		return fmt.Errorf("Failed to load: This type is unknown")
	}
}
开发者ID:saromanov,项目名称:goconfig,代码行数:35,代码来源:goconfig.go


示例5: Parse

// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
	// Decode the rules
	p := &Policy{}
	if rules == "" {
		// Hot path for empty rules
		return p, nil
	}

	if err := hcl.Decode(p, rules); err != nil {
		return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
	}

	// Validate the key policy
	for _, kp := range p.Keys {
		switch kp.Policy {
		case KeyPolicyDeny:
		case KeyPolicyRead:
		case KeyPolicyWrite:
		default:
			return nil, fmt.Errorf("Invalid key policy: %#v", kp)
		}
	}

	// Validate the service policy
	for _, sp := range p.Services {
		switch sp.Policy {
		case ServicePolicyDeny:
		case ServicePolicyRead:
		case ServicePolicyWrite:
		default:
			return nil, fmt.Errorf("Invalid service policy: %#v", sp)
		}
	}

	// Validate the user event policies
	for _, ep := range p.Events {
		switch ep.Policy {
		case EventPolicyRead:
		case EventPolicyWrite:
		case EventPolicyDeny:
		default:
			return nil, fmt.Errorf("Invalid event policy: %#v", ep)
		}
	}

	// Validate the keyring policy
	switch p.Keyring {
	case KeyringPolicyRead:
	case KeyringPolicyWrite:
	case KeyringPolicyDeny:
	case "": // Special case to allow omitting the keyring policy
	default:
		return nil, fmt.Errorf("Invalid keyring policy: %#v", p.Keyring)
	}

	return p, nil
}
开发者ID:sid11693,项目名称:consul,代码行数:60,代码来源:policy.go


示例6: FromString

func FromString(filename string, contents string) (*Config, error) {
	config := Config{}
	err := hcl.Decode(&config, contents)
	if err != nil {
		return nil, err
	}

	config.SourceFilename = filename
	return &config, nil
}
开发者ID:fogforge,项目名称:fogforge,代码行数:10,代码来源:parser.go


示例7: LoadTerraformConfig

func LoadTerraformConfig(path string) (*TerraformConfig, error) {
	var value TerraformConfig

	if _, err := os.Stat(path); err != nil {
		return nil, err
	}
	err := hcl.Decode(&value, readFile(path))
	if err != nil {
		return nil, err
	}
	return &value, nil
}
开发者ID:nadnerb,项目名称:terraform_config,代码行数:12,代码来源:config.go


示例8: Parse

// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
	// Decode the rules
	p := &Policy{}
	if rules == "" {
		// Hot path for empty rules
		return p, nil
	}

	if err := hcl.Decode(p, rules); err != nil {
		return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
	}

	// Validate the key policy
	for _, kp := range p.Keys {
		if !isPolicyValid(kp.Policy) {
			return nil, fmt.Errorf("Invalid key policy: %#v", kp)
		}
	}

	// Validate the service policy
	for _, sp := range p.Services {
		if !isPolicyValid(sp.Policy) {
			return nil, fmt.Errorf("Invalid service policy: %#v", sp)
		}
	}

	// Validate the user event policies
	for _, ep := range p.Events {
		if !isPolicyValid(ep.Policy) {
			return nil, fmt.Errorf("Invalid event policy: %#v", ep)
		}
	}

	// Validate the prepared query policies
	for _, pq := range p.PreparedQueries {
		if !isPolicyValid(pq.Policy) {
			return nil, fmt.Errorf("Invalid query policy: %#v", pq)
		}
	}

	// Validate the keyring policy - this one is allowed to be empty
	if p.Keyring != "" && !isPolicyValid(p.Keyring) {
		return nil, fmt.Errorf("Invalid keyring policy: %#v", p.Keyring)
	}

	// Validate the operator policy - this one is allowed to be empty
	if p.Operator != "" && !isPolicyValid(p.Operator) {
		return nil, fmt.Errorf("Invalid operator policy: %#v", p.Operator)
	}

	return p, nil
}
开发者ID:pulcy,项目名称:vault-monkey,代码行数:55,代码来源:policy.go


示例9: LoadConfigFile

func LoadConfigFile(configFile string) Config {
	var conf Config

	configData, err := ioutil.ReadFile(configFile)
	if err != nil {
		log.Fatalf("Error: Couldn't read config file %s: %s", configFile, err)
	}

	err = hcl.Decode(&conf, string(configData))
	if err != nil {
		log.Fatalf("Error parsing config file %s: %s", configFile, err)
	}

	return conf
}
开发者ID:volker-fr,项目名称:twitter2rss,代码行数:15,代码来源:config.go


示例10: InitializeConfig

func InitializeConfig() *Config {
	var cfg Config
	cfgData, err := ioutil.ReadFile(CfgFile)
	if err != nil {
		log.Fatalln("Unable to locate Config File. make sure you specify it using the --config flag")
		return nil
	}
	err = hcl.Decode(&cfg, string(cfgData))

	if err != nil {
		log.Fatalln("Unable to parse Config File.")
		return nil
	}

	return &cfg
}
开发者ID:ChrisMcKenzie,项目名称:dropship,代码行数:16,代码来源:dropship.go


示例11: parseVariableAsHCL

// parseVariableAsHCL parses the value of a single variable as would have been specified
// on the command line via -var or in an environment variable named TF_VAR_x, where x is
// the name of the variable. In order to get around the restriction of HCL requiring a
// top level object, we prepend a sentinel key, decode the user-specified value as its
// value and pull the value back out of the resulting map.
func parseVariableAsHCL(name string, input string, targetType config.VariableType) (interface{}, error) {
	// expecting a string so don't decode anything, just strip quotes
	if targetType == config.VariableTypeString {
		return strings.Trim(input, `"`), nil
	}

	// return empty types
	if strings.TrimSpace(input) == "" {
		switch targetType {
		case config.VariableTypeList:
			return []interface{}{}, nil
		case config.VariableTypeMap:
			return make(map[string]interface{}), nil
		}
	}

	const sentinelValue = "SENTINEL_TERRAFORM_VAR_OVERRIDE_KEY"
	inputWithSentinal := fmt.Sprintf("%s = %s", sentinelValue, input)

	var decoded map[string]interface{}
	err := hcl.Decode(&decoded, inputWithSentinal)
	if err != nil {
		return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL: %s", name, input, err)
	}

	if len(decoded) != 1 {
		return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. Only one value may be specified.", name, input)
	}

	parsedValue, ok := decoded[sentinelValue]
	if !ok {
		return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. One value must be specified.", name, input)
	}

	switch targetType {
	case config.VariableTypeList:
		return parsedValue, nil
	case config.VariableTypeMap:
		if list, ok := parsedValue.([]map[string]interface{}); ok {
			return list[0], nil
		}

		return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. One value must be specified.", name, input)
	default:
		panic(fmt.Errorf("unknown type %s", targetType.Printable()))
	}
}
开发者ID:Originate,项目名称:terraform,代码行数:52,代码来源:context.go


示例12: Parse

// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
	// Decode the rules
	p := &Policy{Raw: rules}
	if err := hcl.Decode(p, rules); err != nil {
		return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
	}

	// Validate the path policy
	for _, pc := range p.Paths {
		// Strip the glob character if found
		if strings.HasSuffix(pc.Prefix, "*") {
			pc.Prefix = strings.TrimSuffix(pc.Prefix, "*")
			pc.Glob = true
		}

		// Map old-style policies into capabilities
		switch pc.Policy {
		case OldDenyPathPolicy:
			pc.Capabilities = []string{DenyCapability}
		case OldReadPathPolicy:
			pc.Capabilities = append(pc.Capabilities, []string{ReadCapability, ListCapability}...)
		case OldWritePathPolicy:
			pc.Capabilities = append(pc.Capabilities, []string{CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability}...)
		case OldSudoPathPolicy:
			pc.Capabilities = append(pc.Capabilities, []string{CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability}...)
		}

		// Initialize the map
		pc.CapabilitiesBitmap = 0
		for _, cap := range pc.Capabilities {
			switch cap {
			// If it's deny, don't include any other capability
			case DenyCapability:
				pc.Capabilities = []string{DenyCapability}
				pc.CapabilitiesBitmap = DenyCapabilityInt
				goto PathFinished
			case CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability:
				pc.CapabilitiesBitmap |= cap2Int[cap]
			default:
				return nil, fmt.Errorf("Invalid capability: %#v", pc)
			}
		}

	PathFinished:
	}
	return p, nil
}
开发者ID:lagging,项目名称:vault,代码行数:50,代码来源:policy.go


示例13: applyConfigFile

func applyConfigFile(options *Options, filePath string) error {
	filePath = ExpandHomeDir(filePath)
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		return err
	}

	fileString := []byte{}
	log.Printf("Loading config file at: %s", filePath)
	fileString, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
	}

	config := make(map[string]interface{})
	hcl.Decode(&config, string(fileString))
	o := structs.New(options)
	for _, name := range o.Names() {
		configName := strings.ToLower(strings.Join(camelcase.Split(name), "_"))
		if val, ok := config[configName]; ok {
			field, ok := o.FieldOk(name)
			if !ok {
				return errors.New("No such option: " + name)
			}

			var err error
			if name == "Preferences" {
				prefs := val.([]map[string]interface{})[0]
				htermPrefs := make(map[string]interface{})
				for key, value := range prefs {
					htermPrefs[strings.Replace(key, "_", "-", -1)] = value
				}
				err = field.Set(htermPrefs)
			} else {
				err = field.Set(val)
			}

			if err != nil {
				return err
			}

		}
	}

	return nil
}
开发者ID:ujuettner,项目名称:gotty,代码行数:45,代码来源:app.go


示例14: initConfig

func initConfig() Config {
	var configPath = os.Getenv("HOME")
	var c Config
	var err error

	config, err := ioutil.ReadFile(filepath.Join(configPath, configFile))
	if err != nil {
		log.Printf("Error parsing config: %s", err)
		configUsage()
	}

	err = hcl.Decode(&c, string(config))
	if err != nil {
		log.Fatalf("Configuration decode error: %s", err)
	}

	return c
}
开发者ID:promiseofcake,项目名称:merged-prs,代码行数:18,代码来源:config.go


示例15: readConfig

func readConfig() *Config {
	bts, err := ioutil.ReadFile(Path())

	if err != nil {
		printer.SayErr("Could not read %s", Path())
		os.Exit(1)
	}

	var cfg *Config
	defaults := DefaultConfig()

	err = hcl.Decode(&cfg, string(bts[:]))

	if err != nil {
		printer.SayErr("[dcdr] config parse error %+v", err)
		os.Exit(1)
	}

	if cfg.Namespace == "" {
		cfg.Namespace = defaults.Namespace
	}

	if cfg.Username == "" {
		cfg.Username = defaults.Username
	}

	if cfg.Watcher.OutputPath == "" {
		cfg.Watcher.OutputPath = defaults.Watcher.OutputPath
	}

	if cfg.Server.Host == "" {
		cfg.Server.Host = defaults.Server.Host
	}

	if cfg.Server.Endpoint == "" {
		cfg.Server.Endpoint = defaults.Server.Endpoint
	}

	if cfg.Server.JSONRoot == "" {
		cfg.Server.JSONRoot = defaults.Server.JSONRoot
	}

	return cfg
}
开发者ID:vsco,项目名称:dcdr,代码行数:44,代码来源:config.go


示例16: ApplyConfigFile

func ApplyConfigFile(options *Options, filePath string) error {
	filePath = ExpandHomeDir(filePath)
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		return err
	}

	fileString := []byte{}
	log.Printf("Loading config file at: %s", filePath)
	fileString, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
	}

	if err := hcl.Decode(options, string(fileString)); err != nil {
		return err
	}

	return nil
}
开发者ID:rdterner,项目名称:gotty,代码行数:19,代码来源:app.go


示例17: Parse

// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
	// Decode the rules
	p := &Policy{Raw: rules}
	if err := hcl.Decode(p, rules); err != nil {
		return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
	}

	// Validate the path policy
	for _, pp := range p.Paths {
		switch pp.Policy {
		case PathPolicyDeny:
		case PathPolicyRead:
		case PathPolicyWrite:
		case PathPolicySudo:
		default:
			return nil, fmt.Errorf("Invalid path policy: %#v", pp)
		}
	}
	return p, nil
}
开发者ID:worldspawn,项目名称:vault,代码行数:23,代码来源:policy.go


示例18: loadProfileFile

func loadProfileFile(options *Options) (map[string]interface{}, error) {
	prefString := []byte{}
	prefPath := options.ProfileFile
	if options.ProfileFile == DefaultOptions.ProfileFile {
		prefPath = os.Getenv("HOME") + "/.gotty.prf"
	}
	if _, err := os.Stat(prefPath); os.IsNotExist(err) {
		if options.ProfileFile != DefaultOptions.ProfileFile {
			return nil, err
		}
	} else {
		log.Printf("Loading profile path: %s", prefPath)
		prefString, _ = ioutil.ReadFile(prefPath)
	}
	var prefMap map[string]interface{}
	err := hcl.Decode(&prefMap, string(prefString))
	if err != nil {
		return nil, err
	}
	return prefMap, nil
}
开发者ID:nkiraly,项目名称:gotty,代码行数:21,代码来源:app.go


示例19: main

func main() {
	configFile := flag.String("config", "terf.conf", "path to the terf configuration file")
	configProfile := flag.String("profile", "development", "configuration profile to use")
	flag.Parse()

	// Load the configuration file.
	var config Config
	p, err := ioutil.ReadFile(*configFile)
	if err != nil {
		glog.Fatalln("failed to read config file:", err)
	}
	if err := hcl.Decode(&config, string(p)); err != nil {
		glog.Fatalln("failed to decode config file:", err)
	}
	profile, ok := config[*configProfile]
	if !ok {
		glog.Fatalf("no such config profile %q", *configProfile)
	}

	glog.Infoln("connecting to database")

	tplGlob := filepath.Join(profile.Terf.TemplateDir, "*.html")
	glog.Infof("loading templates %q", tplGlob)
	Templates, err = template.ParseGlob(tplGlob)
	if err != nil {
		glog.Fatalln(err)
	}

	http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir(profile.Terf.StaticDir))))
	http.HandleFunc("/", handleIndex)

	glog.Infoln("listening on", profile.Terf.ListenAddr)
	if err := http.ListenAndServe(profile.Terf.ListenAddr, nil); err != nil {
		glog.Fatalln(err)
	}
	glog.Infoln("terminated gracefully")
}
开发者ID:nesv,项目名称:terf,代码行数:37,代码来源:main.go


示例20: UpdateConfig

func (cp ConfigParser) UpdateConfig(hclText string, result *Config) error {
	var tmp Config
	tmp = *result
	if err := hcl.Decode(&tmp, hclText); err != nil {
		return err
	}

	if tmp.InfluxDB.CheckLapse == 0 {
		tmp.InfluxDB.CheckLapse = DefaultConfig.InfluxDB.CheckLapse
	}

	if cp.AllowDNS && tmp.MesosDNS != nil {
		resolver := NewDNSResolver(&tmp)
		if err := resolver.resolve(); err != nil {
			return err
		}

	}

	log.Printf("%+v\n", tmp)
	*result = tmp

	return nil
}
开发者ID:kpacha,项目名称:mesos-influxdb-collector,代码行数:24,代码来源:configuration.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang hcl.DecodeObject函数代码示例发布时间:2022-05-23
下一篇:
Golang golang-lru.New函数代码示例发布时间: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