當前位置: 首頁>>代碼示例>>Golang>>正文


Golang v1.Unmarshal函數代碼示例

本文整理匯總了Golang中gopkg/in/yaml/v1.Unmarshal函數的典型用法代碼示例。如果您正苦於以下問題:Golang Unmarshal函數的具體用法?Golang Unmarshal怎麽用?Golang Unmarshal使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Unmarshal函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestGetConfig

func (s *GetSuite) TestGetConfig(c *gc.C) {
	sch := s.AddTestingCharm(c, "dummy")
	svc := s.AddTestingService(c, "dummy-service", sch)
	err := svc.UpdateConfigSettings(charm.Settings{"title": "Nearly There"})
	c.Assert(err, jc.ErrorIsNil)
	for _, t := range getTests {
		ctx := coretesting.Context(c)
		code := cmd.Main(envcmd.Wrap(&GetCommand{}), ctx, []string{t.service})
		c.Check(code, gc.Equals, 0)
		c.Assert(ctx.Stderr.(*bytes.Buffer).String(), gc.Equals, "")
		// round trip via goyaml to avoid being sucked into a quagmire of
		// map[interface{}]interface{} vs map[string]interface{}. This is
		// also required if we add json support to this command.
		buf, err := goyaml.Marshal(t.expected)
		c.Assert(err, jc.ErrorIsNil)
		expected := make(map[string]interface{})
		err = goyaml.Unmarshal(buf, &expected)
		c.Assert(err, jc.ErrorIsNil)

		actual := make(map[string]interface{})
		err = goyaml.Unmarshal(ctx.Stdout.(*bytes.Buffer).Bytes(), &actual)
		c.Assert(err, jc.ErrorIsNil)
		c.Assert(actual, gc.DeepEquals, expected)
	}
}
開發者ID:kakamessi99,項目名稱:juju,代碼行數:25,代碼來源:get_test.go

示例2: readSettings

func (c *RelationSetCommand) readSettings(in io.Reader) (map[string]string, error) {
	data, err := ioutil.ReadAll(in)
	if err != nil {
		return nil, errors.Trace(err)
	}

	skipValidation := false // for debugging
	if !skipValidation {
		// Can this validation be done more simply or efficiently?

		var scalar string
		if err := goyaml.Unmarshal(data, &scalar); err != nil {
			return nil, errors.Trace(err)
		}
		if scalar != "" {
			return nil, errors.Errorf("expected YAML map, got %q", scalar)
		}

		var sequence []string
		if err := goyaml.Unmarshal(data, &sequence); err != nil {
			return nil, errors.Trace(err)
		}
		if len(sequence) != 0 {
			return nil, errors.Errorf("expected YAML map, got %#v", sequence)
		}
	}

	kvs := make(map[string]string)
	if err := goyaml.Unmarshal(data, kvs); err != nil {
		return nil, errors.Trace(err)
	}

	return kvs, nil
}
開發者ID:ktsakalozos,項目名稱:juju,代碼行數:34,代碼來源:relation-set.go

示例3: ParseFile

func (cfg *conf) ParseFile(filename string) error {

	file, err := os.Open(filename)
	if err != nil {
		return fmt.Errorf("Failed to open file '%s': %s", filename, err.Error())
	}
	defer file.Close()

	bytes, err := ioutil.ReadAll(file)
	if err != nil {
		return fmt.Errorf("Error on reading from file '%s': %s", filename, err.Error())
	}

	err = yaml.Unmarshal(bytes, &(cfg.set))
	if err != nil {
		return fmt.Errorf("Error on parsing configuration file '%s': %s", filename, err.Error())
	}

	err = cfg.Validate()
	if err != nil {
		return fmt.Errorf("Failed to validate configuration: %s", err.Error())
	}

	return nil
}
開發者ID:ivartj,項目名稱:norske-irc-kanaler.com,代碼行數:25,代碼來源:conf.go

示例4: TestOutputFormatKey

func (s *storageGetSuite) TestOutputFormatKey(c *gc.C) {
	for i, t := range storageGetTests {
		c.Logf("test %d: %#v", i, t.args)
		hctx, _ := s.newHookContext()
		com, err := jujuc.NewCommand(hctx, cmdString("storage-get"))
		c.Assert(err, jc.ErrorIsNil)
		ctx := testing.Context(c)
		code := cmd.Main(com, ctx, t.args)
		c.Assert(code, gc.Equals, 0)
		c.Assert(bufferString(ctx.Stderr), gc.Equals, "")

		var out interface{}
		var outMap map[string]interface{}
		switch t.format {
		case formatYaml:
			c.Assert(goyaml.Unmarshal(bufferBytes(ctx.Stdout), &outMap), gc.IsNil)
			out = outMap
		case formatJson:
			c.Assert(json.Unmarshal(bufferBytes(ctx.Stdout), &outMap), gc.IsNil)
			out = outMap
		default:
			out = string(bufferBytes(ctx.Stdout))
		}
		c.Assert(out, gc.DeepEquals, t.out)
	}
}
開發者ID:Pankov404,項目名稱:juju,代碼行數:26,代碼來源:storage-get_test.go

示例5: loadConfig

func loadConfig(agentConfig agent.Config) (*config, error) {
	config := &config{
		storageDir:  agentConfig.Value(StorageDir),
		storageAddr: agentConfig.Value(StorageAddr),
		authkey:     agentConfig.Value(StorageAuthKey),
	}

	caCertPEM := agentConfig.Value(StorageCACert)
	if len(caCertPEM) > 0 {
		config.caCertPEM = caCertPEM
	}

	caKeyPEM := agentConfig.Value(StorageCAKey)
	if len(caKeyPEM) > 0 {
		config.caKeyPEM = caKeyPEM
	}

	hostnames := agentConfig.Value(StorageHostnames)
	if len(hostnames) > 0 {
		err := goyaml.Unmarshal([]byte(hostnames), &config.hostnames)
		if err != nil {
			return nil, err
		}
	}

	return config, nil
}
開發者ID:kapilt,項目名稱:juju,代碼行數:27,代碼來源:config.go

示例6: removeEnvUUIDFromAgentConfig

func (s *migrateAgentEnvUUIDSuite) removeEnvUUIDFromAgentConfig(c *gc.C) {
	// Read the file in as simple map[string]interface{} and delete
	// the element, and write it back out again.

	// First step, read the file contents.
	filename := agent.ConfigPath(agent.DefaultDataDir, s.machine.Tag())
	data, err := ioutil.ReadFile(filename)
	c.Assert(err, jc.ErrorIsNil)
	c.Logf("Data in:\n\n%s\n", data)

	// Parse it into the map.
	var content map[string]interface{}
	err = goyaml.Unmarshal(data, &content)
	c.Assert(err, jc.ErrorIsNil)

	// Remove the environment value, and marshal back into bytes.
	delete(content, "environment")
	data, err = goyaml.Marshal(content)
	c.Assert(err, jc.ErrorIsNil)

	// Write the yaml back out remembering to add the format prefix.
	data = append([]byte("# format 1.18\n"), data...)
	c.Logf("Data out:\n\n%s\n", data)
	err = ioutil.WriteFile(filename, data, 0644)
	c.Assert(err, jc.ErrorIsNil)

	// Reset test attributes.
	cfg, err := agent.ReadConfig(filename)
	c.Assert(err, jc.ErrorIsNil)
	s.ctx.realAgentConfig = cfg
}
開發者ID:Pankov404,項目名稱:juju,代碼行數:31,代碼來源:agentconfig_test.go

示例7: ParseConfigData

func ParseConfigData(data []byte) (*Config, error) {
	var cfg Config
	if err := yaml.Unmarshal([]byte(data), &cfg); err != nil {
		return nil, err
	}
	return &cfg, nil
}
開發者ID:tanxunrong,項目名稱:mixer,代碼行數:7,代碼來源:config.go

示例8: TestCloudInitConfigureBootstrapLogging

func (*cloudinitSuite) TestCloudInitConfigureBootstrapLogging(c *gc.C) {
	loggo.GetLogger("").SetLogLevel(loggo.INFO)
	instanceConfig := minimalInstanceConfig()
	instanceConfig.Config = minimalConfig(c)

	cloudcfg, err := cloudinit.New(instanceConfig.Series)
	c.Assert(err, jc.ErrorIsNil)
	udata, err := cloudconfig.NewUserdataConfig(&instanceConfig, cloudcfg)

	c.Assert(err, jc.ErrorIsNil)
	err = udata.Configure()
	c.Assert(err, jc.ErrorIsNil)
	data, err := cloudcfg.RenderYAML()
	c.Assert(err, jc.ErrorIsNil)
	configKeyValues := make(map[interface{}]interface{})
	err = goyaml.Unmarshal(data, &configKeyValues)
	c.Assert(err, jc.ErrorIsNil)

	scripts := getScripts(configKeyValues)
	for i, script := range scripts {
		if strings.Contains(script, "bootstrap") {
			c.Logf("scripts[%d]: %q", i, script)
		}
	}
	expected := "jujud bootstrap-state --data-dir '.*' --env-config '.*'" +
		" --instance-id '.*' --constraints 'mem=2048M' --show-log"
	assertScriptMatch(c, scripts, expected, false)
}
開發者ID:Pankov404,項目名稱:juju,代碼行數:28,代碼來源:userdatacfg_test.go

示例9: ReadEnvironsBytes

// ReadEnvironsBytes parses the contents of an environments.yaml file
// and returns its representation. An environment with an unknown type
// will only generate an error when New is called for that environment.
// Attributes for environments with known types are checked.
func ReadEnvironsBytes(data []byte) (*Environs, error) {
	var raw struct {
		Default      string
		Environments map[string]map[string]interface{}
	}
	err := goyaml.Unmarshal(data, &raw)
	if err != nil {
		return nil, err
	}

	if raw.Default != "" && raw.Environments[raw.Default] == nil {
		return nil, fmt.Errorf("default environment %q does not exist", raw.Default)
	}
	if raw.Default == "" {
		// If there's a single environment, then we get the default
		// automatically.
		if len(raw.Environments) == 1 {
			for name := range raw.Environments {
				raw.Default = name
				break
			}
		}
	}
	for name, attrs := range raw.Environments {
		// store the name of the this environment in the config itself
		// so that providers can see it.
		attrs["name"] = name
	}
	return &Environs{raw.Default, raw.Environments}, nil
}
開發者ID:zhouqt,項目名稱:juju,代碼行數:34,代碼來源:config.go

示例10: main

func main() {
	flag.Parse()

	configs := &inception.Configs{}
	input, err := ioutil.ReadFile(*yml)
	if err != nil {
		log.Fatalf("Opening config failed: %v", err)
	}
	if err := yaml.Unmarshal(input, configs); err != nil {
		log.Fatalf("Parsing config failed: %v", err)
	}

	types, err := inception.Inception(*configs)
	if err != nil {
		log.Fatalf("Loading input failed: %v", err)
	}

	if err := os.Chdir(*out); err != nil {
		log.Fatalf("Changing to output directory %q failed: %v", *out, err)
	}

	if err := ioutil.WriteFile("Go2Elm.elm", []byte(Go2Elm), 0640); err != nil {
		log.Fatalf("Writing runtime failed: %v", err)
	}

	visitor := &Generator{}
	visitor.Visit(types)
	for pkg, buffer := range visitor.Buffers() {
		parts := strings.Split(pkg, ".")
		os.MkdirAll(filepath.Join(parts[0:len(parts)-1]...), 0750)
		if err := ioutil.WriteFile(filepath.Join(parts...)+".elm", buffer.Bytes(), 0640); err != nil {
			log.Fatalf("Writing output failed: %v", err)
		}
	}
}
開發者ID:shutej,項目名稱:go2elm,代碼行數:35,代碼來源:main.go

示例11: readJENVFile

func (d *diskStore) readJENVFile(envName string) (*environInfo, error) {
	path := jenvFilename(d.dir, envName)
	data, err := ioutil.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, errors.NotFoundf("environment %q", envName)
		}
		return nil, err
	}
	var info environInfo
	info.path = path
	if len(data) == 0 {
		return &info, nil
	}
	var values EnvironInfoData
	if err := goyaml.Unmarshal(data, &values); err != nil {
		return nil, errors.Annotatef(err, "error unmarshalling %q", path)
	}
	info.name = envName
	info.user = values.User
	info.credentials = values.Password
	info.environmentUUID = values.EnvironUUID
	info.caCert = values.CACert
	info.apiEndpoints = values.StateServers
	info.bootstrapConfig = values.Config

	info.initialized = true
	return &info, nil
}
開發者ID:kapilt,項目名稱:juju,代碼行數:29,代碼來源:disk.go

示例12: ParseSettingsYAML

// ParseSettingsYAML returns settings derived from the supplied YAML data. The
// YAML must unmarshal to a map of strings to settings data; the supplied key
// must be present in the map, and must point to a map in which every value
// must have, or be a string parseable to, the correct type for the associated
// config option. Empty strings and nil values are both interpreted as nil.
func (c *Config) ParseSettingsYAML(yamlData []byte, key string) (Settings, error) {
	var allSettings map[string]Settings
	if err := goyaml.Unmarshal(yamlData, &allSettings); err != nil {
		return nil, fmt.Errorf("cannot parse settings data: %v", err)
	}
	settings, ok := allSettings[key]
	if !ok {
		return nil, fmt.Errorf("no settings found for %q", key)
	}
	out := make(Settings)
	for name, value := range settings {
		option, err := c.option(name)
		if err != nil {
			return nil, err
		}
		// Accept string values for compatibility with python.
		if str, ok := value.(string); ok {
			if value, err = option.parse(name, str); err != nil {
				return nil, err
			}
		} else if value, err = option.validate(name, value); err != nil {
			return nil, err
		}
		out[name] = value
	}
	return out, nil
}
開發者ID:juju,項目名稱:charm,代碼行數:32,代碼來源:config.go

示例13: Set

// Set decodes the base64 value into yaml then expands that into a map.
func (v *yamlBase64Value) Set(value string) error {
	decoded, err := base64.StdEncoding.DecodeString(value)
	if err != nil {
		return err
	}
	return goyaml.Unmarshal(decoded, v)
}
開發者ID:kapilt,項目名稱:juju,代碼行數:8,代碼來源:bootstrap.go

示例14: ReadYaml

// ReadYaml unmarshals the yaml contained in the file at path into obj. See
// goyaml.Unmarshal.
func ReadYaml(path string, obj interface{}) error {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	return goyaml.Unmarshal(data, obj)
}
開發者ID:wwitzel3,項目名稱:utils,代碼行數:9,代碼來源:trivial.go

示例15: ReadConfig

// ReadConfig reads a Config in YAML format.
func ReadConfig(r io.Reader) (*Config, error) {
	data, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	var config *Config
	if err := goyaml.Unmarshal(data, &config); err != nil {
		return nil, err
	}
	if config == nil {
		return nil, fmt.Errorf("invalid config: empty configuration")
	}
	for name, option := range config.Options {
		switch option.Type {
		case "string", "int", "float", "boolean":
		case "":
			// Missing type is valid in python.
			option.Type = "string"
		default:
			return nil, fmt.Errorf("invalid config: option %q has unknown type %q", name, option.Type)
		}
		def := option.Default
		if def == "" && option.Type == "string" {
			// Skip normal validation for compatibility with pyjuju.
		} else if option.Default, err = option.validate(name, def); err != nil {
			option.error(&err, name, def)
			return nil, fmt.Errorf("invalid config default: %v", err)
		}
		config.Options[name] = option
	}
	return config, nil
}
開發者ID:juju,項目名稱:charm,代碼行數:33,代碼來源:config.go


注:本文中的gopkg/in/yaml/v1.Unmarshal函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。