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


Golang goyaml.Marshal函數代碼示例

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


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

示例1: diff

func diff(aFilePath, bFilePath string) {
	aFile, err := ioutil.ReadFile(aFilePath)
	if err != nil {
		log.Fatalln("error reading a:", err)
	}

	aYAML, err := yaml.Parse(aFile)
	if err != nil {
		log.Fatalln("error parsing a:", err)
	}

	bFile, err := ioutil.ReadFile(bFilePath)
	if err != nil {
		log.Fatalln("error reading b:", err)
	}

	bYAML, err := yaml.Parse(bFile)
	if err != nil {
		log.Fatalln("error parsing b:", err)
	}

	diffs := compare.Compare(aYAML, bYAML)

	if len(diffs) == 0 {
		fmt.Println("no differences!")
		return
	}

	for _, diff := range diffs {
		fmt.Println("Difference in", strings.Join(diff.Path, "."))

		if diff.A != nil {
			ayaml, err := goyaml.Marshal(diff.A)
			if err != nil {
				panic(err)
			}

			fmt.Printf("  %s has:\n    \x1b[31m%s\x1b[0m\n", aFilePath, strings.Replace(string(ayaml), "\n", "\n    ", -1))
		}

		if diff.B != nil {
			byaml, err := goyaml.Marshal(diff.B)
			if err != nil {
				panic(err)
			}

			fmt.Printf("  %s has:\n    \x1b[32m%s\x1b[0m\n", bFilePath, strings.Replace(string(byaml), "\n", "\n    ", -1))
		}
	}
}
開發者ID:jbayer,項目名稱:spiff,代碼行數:50,代碼來源:spiff.go

示例2: TestMarshalTypeCache

func (s *S) TestMarshalTypeCache(c *C) {
	var data []byte
	var err error
	func() {
		type T struct{ A int }
		data, err = goyaml.Marshal(&T{})
		c.Assert(err, IsNil)
	}()
	func() {
		type T struct{ B int }
		data, err = goyaml.Marshal(&T{})
		c.Assert(err, IsNil)
	}()
	c.Assert(string(data), Equals, "b: 0\n")
}
開發者ID:9cc9,項目名稱:dea_ng,代碼行數:15,代碼來源:encode_test.go

示例3: SaveAuthToken

func SaveAuthToken(configPath, authtoken string) (err error) {
	// read the configuration
	oldConfigBytes, err := ioutil.ReadFile(configPath)
	if err != nil {
		return
	}

	c := new(Configuration)
	if err = goyaml.Unmarshal(oldConfigBytes, c); err != nil {
		return
	}

	// no need to save, the authtoken is already the correct value
	if c.AuthToken == authtoken {
		return
	}

	// update auth token
	c.AuthToken = authtoken

	// rewrite configuration
	newConfigBytes, err := goyaml.Marshal(c)
	if err != nil {
		return
	}

	err = ioutil.WriteFile(configPath, newConfigBytes, 0600)
	return
}
開發者ID:jedibatman,項目名稱:ngrok,代碼行數:29,代碼來源:config.go

示例4: SaveState

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

示例5: Write

// Write implements EnvironInfo.Write.
func (info *environInfo) Write() error {
	info.mu.Lock()
	defer info.mu.Unlock()
	data, err := goyaml.Marshal(info.EnvInfo)
	if err != nil {
		return errors.Annotate(err, "cannot marshal environment info")
	}
	// Create a temporary file and rename it, so that the data
	// changes atomically.
	parent, _ := filepath.Split(info.path)
	tmpFile, err := ioutil.TempFile(parent, "")
	if err != nil {
		return errors.Annotate(err, "cannot create temporary file")
	}
	_, err = tmpFile.Write(data)
	// N.B. We need to close the file before renaming it
	// otherwise it will fail under Windows with a file-in-use
	// error.
	tmpFile.Close()
	if err != nil {
		return errors.Annotate(err, "cannot write temporary file")
	}
	if err := utils.ReplaceFile(tmpFile.Name(), info.path); err != nil {
		os.Remove(tmpFile.Name())
		return errors.Annotate(err, "cannot rename new environment info file")
	}
	info.initialized = true
	return nil
}
開發者ID:klyachin,項目名稱:juju,代碼行數:30,代碼來源:disk.go

示例6: Reader

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

示例7: renameRelation

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

	replace := func(what map[string]charm.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, Equals, true, Commentf("charm %q does not implement relation %q", charmPath, oldName))

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

	f, err = os.Open(path)
	c.Assert(err, IsNil)
	defer f.Close()
	meta, err = charm.ReadMeta(f)
	c.Assert(err, IsNil)
}
開發者ID:johnvilsack,項目名稱:golang-stuff,代碼行數:31,代碼來源:uniter_test.go

示例8: saveState

func (e *environ) saveState(state *bootstrapState) error {
	data, err := goyaml.Marshal(state)
	if err != nil {
		return err
	}
	return e.Storage().Put(stateFile, bytes.NewBuffer(data), int64(len(data)))
}
開發者ID:prabhakhar,項目名稱:juju-core,代碼行數:7,代碼來源:state.go

示例9: main

func main() {
	var file string
	flag.StringVar(&file, "f", "", "Path to file to convert.")
	flag.Parse()
	if file == "" {
		flag.Usage()
		return
	}
	resource, err := apidef.ParseFile(file)
	if err != nil {
		panic(err)
	}
	data, err := goyaml.Marshal(&resource)
	if err != nil {
		panic(err)
	}
	fileInfo, err := os.Lstat(file)
	if err != nil {
		panic(err)
	}
	file = strings.Replace(file, ".json", ".yml", -1)
	err = ioutil.WriteFile(file, data, fileInfo.Mode())
	if err != nil {
		panic(err)
	}
}
開發者ID:paddyforan,項目名稱:jarvis,代碼行數:26,代碼來源:json_to_yml.go

示例10: marshal

func (formatter_1_18) marshal(config *configInternal) ([]byte, error) {
	format := &format_1_18Serialization{
		Tag:               config.tag,
		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,
	}
	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:jkary,項目名稱:core,代碼行數:30,代碼來源:format-1.18.go

示例11: init

// Load configuration settings and setup database connection
func init() {
	globalSettings := make(map[string]string)
	var confFile string
	flag.StringVar(&confFile, "config", "config.yml", "Path to config file")
	flag.Parse()
	if confFile, err := filepath.Abs(confFile); err != nil {
		log.Printf("Cannot find configuration file '%v', using default settings", confFile)
	} else if raw, err := ioutil.ReadFile(confFile); err != nil {
		log.Printf("[%v] Cannot load configuration file '%v', using default settings", os.Getpid(), confFile)
	} else {
		err := goyaml.Unmarshal(raw, &globalSettings)
		if err != nil {
			log.Printf("Cannot load configuration settings: %v", err)
		}
	}
	for setting, value := range defaultSettings() {
		if _, ok := globalSettings[setting]; !ok {
			globalSettings[setting] = value
		}
	}
	msg, err := goyaml.Marshal(&globalSettings)
	if err != nil {
		log.Fatalf("Could not log settings: %v", err)
	}
	log.Printf("Startup settings:\n%s", msg)

	gotcha.StartSession(globalSettings["mongoHost"], globalSettings["mongoUser"],
		globalSettings["mongoPassword"], globalSettings["environment"])
}
開發者ID:raphael,項目名稱:gotcha,代碼行數:30,代碼來源:application.go

示例12: 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:jameinel,項目名稱:core,代碼行數:8,代碼來源:state.go

示例13: init

func init() {
	cmdInit.Run = func() {
		path, _ := filepath.Abs(ZAS_DIR)
		if _, err := os.Stat(ZAS_DIR); os.IsNotExist(err) {
			os.Mkdir(ZAS_DIR, os.FileMode(ZAS_DEFAULT_DIR_PERM))
			fmt.Printf("Initialized empty %s repository in %s\n", ZAS_NAME, path)
		} else {
			fmt.Printf("Reinitialized existing %s repository in %s\n", ZAS_NAME, path)
		}
		var (
			data []byte
			err  error
		)
		// If default config variable has fields, we store it as ZAS_CONF_FILE (as defined in constants.go).
		// It overwrites every time we invoke init subcommand.
		if len(ZAS_DEFAULT_CONF) > 0 {
			if data, err = yaml.Marshal(&ZAS_DEFAULT_CONF); err != nil {
				panic(err)
			}
		}
		if err := ioutil.WriteFile(ZAS_CONF_FILE, data, os.FileMode(ZAS_DEFAULT_FILE_PERM)); err != nil {
			panic(err)
		}
	}
	cmdInit.Init()
}
開發者ID:kublaj,項目名稱:zas,代碼行數:26,代碼來源:init.go

示例14: TestMarshal

func (s *S) TestMarshal(c *C) {
	for _, item := range marshalTests {
		data, err := goyaml.Marshal(item.value)
		c.Assert(err, IsNil)
		c.Assert(string(data), Equals, item.data)
	}
}
開發者ID:pauek,項目名稱:goyaml,代碼行數:7,代碼來源:encode_test.go

示例15: 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, gc.IsNil)
	for _, t := range getTests {
		ctx := coretesting.Context(c)
		code := cmd.Main(&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, gc.IsNil)
		expected := make(map[string]interface{})
		err = goyaml.Unmarshal(buf, &expected)
		c.Assert(err, gc.IsNil)

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


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