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


Golang v1.Marshal函數代碼示例

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


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

示例1: encode

func (m b64yaml) encode() string {
	data, err := goyaml.Marshal(m)
	if err != nil {
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(data)
}
開發者ID:ktsakalozos,項目名稱:juju,代碼行數:7,代碼來源:bootstrap_test.go

示例2: 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

示例3: marshal

func (formatter_1_18) marshal(config *configInternal) ([]byte, error) {
	format := &format_1_18Serialization{
		Tag:               config.tag.String(),
		DataDir:           config.dataDir,
		LogDir:            config.logDir,
		Jobs:              config.jobs,
		UpgradedToVersion: &config.upgradedToVersion,
		Nonce:             config.nonce,
		CACert:            string(config.caCert),
		OldPassword:       config.oldPassword,
		Values:            config.values,
		PreferIPv6:        config.preferIPv6,
	}
	if config.servingInfo != nil {
		format.StateServerCert = config.servingInfo.Cert
		format.StateServerKey = config.servingInfo.PrivateKey
		format.APIPort = config.servingInfo.APIPort
		format.StatePort = config.servingInfo.StatePort
		format.SharedSecret = config.servingInfo.SharedSecret
		format.SystemIdentity = config.servingInfo.SystemIdentity
	}
	if config.stateDetails != nil {
		format.StateAddresses = config.stateDetails.addresses
		format.StatePassword = config.stateDetails.password
	}
	if config.apiDetails != nil {
		format.APIAddresses = config.apiDetails.addresses
		format.APIPassword = config.apiDetails.password
	}
	return goyaml.Marshal(format)
}
開發者ID:kapilt,項目名稱:juju,代碼行數:31,代碼來源:format-1.18.go

示例4: SaveState

// SaveState writes the given state to the given storage.
func SaveState(storage storage.StorageWriter, state *BootstrapState) error {
	data, err := goyaml.Marshal(state)
	if err != nil {
		return err
	}
	return putState(storage, data)
}
開發者ID:Pankov404,項目名稱:juju,代碼行數:8,代碼來源:state.go

示例5: marshalConfig

// marshalConfig marshals the specified configI interface into yaml
// bytes.
func marshalConfig(configI interface{}, t *testing.T) []byte {
	bytes, err := yaml.Marshal(configI)
	if err != nil {
		t.Fatal(err)
	}
	return bytes
}
開發者ID:Zemnmez,項目名稱:cockroach,代碼行數:9,代碼來源:range_test.go

示例6: runSetUser

// runSetUser invokes the REST API with POST action and username as
// path. Prompts for the password twice on stdin.
// TODO(marc): once we have more fields in the user config, we will need
// to allow changing just some of them (eg: change email, but leave password).
func runSetUser(cmd *cobra.Command, args []string) {
	if len(args) != 1 {
		cmd.Usage()
		return
	}
	hashed, err := security.PromptForPasswordAndHash()
	if err != nil {
		log.Error(err)
		return
	}
	// Build a UserConfig object. RunSetUser expects Yaml.
	// TODO(marc): re-work admin client library to take other encodings.
	pb := &proto.UserConfig{HashedPassword: hashed}
	contents, err := yaml.Marshal(pb)
	if err != nil {
		log.Error(err)
		return
	}
	admin := client.NewAdminClient(&Context.Context, Context.Addr, client.User)
	if err := admin.SetYAML(args[0], string(contents)); err != nil {
		log.Error(err)
		return
	}
	fmt.Printf("Wrote user config for %q\n", args[0])
}
開發者ID:greener98103,項目名稱:cockroach,代碼行數:29,代碼來源:user.go

示例7: renameRelation

func renameRelation(c *gc.C, charmPath, oldName, newName string) {
	path := filepath.Join(charmPath, "metadata.yaml")
	f, err := os.Open(path)
	c.Assert(err, jc.ErrorIsNil)
	defer f.Close()
	meta, err := corecharm.ReadMeta(f)
	c.Assert(err, jc.ErrorIsNil)

	replace := func(what map[string]corecharm.Relation) bool {
		for relName, relation := range what {
			if relName == oldName {
				what[newName] = relation
				delete(what, oldName)
				return true
			}
		}
		return false
	}
	replaced := replace(meta.Provides) || replace(meta.Requires) || replace(meta.Peers)
	c.Assert(replaced, gc.Equals, true, gc.Commentf("charm %q does not implement relation %q", charmPath, oldName))

	newmeta, err := goyaml.Marshal(meta)
	c.Assert(err, jc.ErrorIsNil)
	ioutil.WriteFile(path, newmeta, 0644)

	f, err = os.Open(path)
	c.Assert(err, jc.ErrorIsNil)
	defer f.Close()
	_, err = corecharm.ReadMeta(f)
	c.Assert(err, jc.ErrorIsNil)
}
開發者ID:ktsakalozos,項目名稱:juju,代碼行數:31,代碼來源:util_test.go

示例8: TestSystemLoginCommand

func (s *cmdSystemSuite) TestSystemLoginCommand(c *gc.C) {
	user := s.Factory.MakeUser(c, &factory.UserParams{
		NoEnvUser: true,
		Password:  "super-secret",
	})
	apiInfo := s.APIInfo(c)
	serverFile := envcmd.ServerFile{
		Addresses: apiInfo.Addrs,
		CACert:    apiInfo.CACert,
		Username:  user.Name(),
		Password:  "super-secret",
	}
	serverFilePath := filepath.Join(c.MkDir(), "server.yaml")
	content, err := goyaml.Marshal(serverFile)
	c.Assert(err, jc.ErrorIsNil)
	err = ioutil.WriteFile(serverFilePath, []byte(content), 0644)
	c.Assert(err, jc.ErrorIsNil)

	s.run(c, "login", "--server", serverFilePath, "just-a-system")

	// Make sure that the saved server details are sufficient to connect
	// to the api server.
	api, err := juju.NewAPIFromName("just-a-system")
	c.Assert(err, jc.ErrorIsNil)
	api.Close()
}
開發者ID:frankban,項目名稱:juju-tmp,代碼行數:26,代碼來源:cmd_juju_system_test.go

示例9: 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

示例10: Reader

func (yh YamlHacker) Reader() io.Reader {
	data, err := goyaml.Marshal(yh)
	if err != nil {
		panic(err)
	}
	return bytes.NewBuffer(data)
}
開發者ID:ktsakalozos,項目名稱:charm,代碼行數:7,代碼來源:charm_test.go

示例11: base64yaml

func base64yaml(m *config.Config) string {
	data, err := goyaml.Marshal(m.AllAttrs())
	if err != nil {
		// can't happen, these values have been validated a number of times
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(data)
}
開發者ID:ktsakalozos,項目名稱:juju,代碼行數:8,代碼來源:userdatacfg_unix.go

示例12: writeCacheFile

func writeCacheFile(filename string, content CacheFile) error {
	data, err := goyaml.Marshal(content)
	if err != nil {
		return errors.Annotate(err, "cannot marshal cache file")
	}
	err = ioutil.WriteFile(filename, data, 0600)
	return errors.Annotate(err, "cannot write file")
}
開發者ID:claudiu-coblis,項目名稱:juju,代碼行數:8,代碼來源:cachefile.go

示例13: Example_acctContentTypes

// Example_acctContentTypes verifies that the Accept header can be used
// to control the format of the response and the Content-Type header
// can be used to specify the format of the request.
func Example_acctContentTypes() {
	_, stopper := startAdminServer()
	defer stopper.Stop()

	config := &proto.AcctConfig{}
	err := yaml.Unmarshal([]byte(testAcctConfig), config)
	if err != nil {
		fmt.Println(err)
	}
	testCases := []struct {
		contentType, accept string
	}{
		{util.JSONContentType, util.JSONContentType},
		{util.YAMLContentType, util.JSONContentType},
		{util.JSONContentType, util.YAMLContentType},
		{util.YAMLContentType, util.YAMLContentType},
	}

	for i, test := range testCases {
		key := fmt.Sprintf("/test%d", i)

		var body []byte
		if test.contentType == util.JSONContentType {
			if body, err = json.MarshalIndent(config, "", "  "); err != nil {
				fmt.Println(err)
			}
		} else {
			if body, err = yaml.Marshal(config); err != nil {
				fmt.Println(err)
			}
		}
		req, err := http.NewRequest("POST", fmt.Sprintf("%s://%s%s%s", testContext.RequestScheme(), testContext.Addr,
			acctPathPrefix, key), bytes.NewReader(body))
		req.Header.Add(util.ContentTypeHeader, test.contentType)
		if _, err = sendAdminRequest(testContext, req); err != nil {
			fmt.Println(err)
		}

		req, err = http.NewRequest("GET", fmt.Sprintf("%s://%s%s%s", testContext.RequestScheme(), testContext.Addr,
			acctPathPrefix, key), nil)
		req.Header.Add(util.AcceptHeader, test.accept)
		if body, err = sendAdminRequest(testContext, req); err != nil {
			fmt.Println(err)
		}
		fmt.Println(string(body))
	}
	// Output:
	// {
	//   "cluster_id": "test"
	// }
	// {
	//   "cluster_id": "test"
	// }
	// cluster_id: test
	//
	// cluster_id: test
}
開發者ID:chinnitv,項目名稱:cockroach,代碼行數:60,代碼來源:accounting_test.go

示例14: encodeArgs

func encodeArgs(hooks []string) []byte {
	// Marshal to YAML, then encode in base64 to avoid shell escapes.
	yamlArgs, err := goyaml.Marshal(hookArgs{Hooks: hooks})
	if err != nil {
		// This should not happen: we're in full control.
		panic(err)
	}
	return yamlArgs
}
開發者ID:kapilt,項目名稱:juju,代碼行數:9,代碼來源:client.go

示例15: Encode

// Encode - Encodes an action into a writer.
func (e *Encoder) Encode(a *action.Action) (err error) {
	list := formatAction(a)
	body, err := yaml2.Marshal(list)
	if err != nil {
		return
	}
	_, err = e.Writer.Write(body)
	return
}
開發者ID:crackcomm,項目名稱:go-actions,代碼行數:10,代碼來源:yaml.go


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