本文整理匯總了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)
}
示例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
}
示例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)
}
示例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)
}
示例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
}
示例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])
}
示例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)
}
示例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()
}
示例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)
}
}
示例10: Reader
func (yh YamlHacker) Reader() io.Reader {
data, err := goyaml.Marshal(yh)
if err != nil {
panic(err)
}
return bytes.NewBuffer(data)
}
示例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)
}
示例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")
}
示例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
}
示例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
}
示例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
}