本文整理匯總了Golang中gopkg/in/yaml/v2.Marshal函數的典型用法代碼示例。如果您正苦於以下問題:Golang Marshal函數的具體用法?Golang Marshal怎麽用?Golang Marshal使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Marshal函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
t := CircleCIConfig{}
err := yaml.Unmarshal([]byte(data), &t)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- t:\n%v\n\n", t)
d, err := yaml.Marshal(&t)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- t dump:\n%s\n\n", string(d))
m := make(map[interface{}]interface{})
err = yaml.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m:\n%v\n\n", m)
d, err = yaml.Marshal(&m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m dump:\n%s\n\n", string(d))
for _, p := range t.Test.Pre {
fmt.Println(p)
}
}
示例2: 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)
}
示例3: toYAML
// toYAML converts the given structure into a deeply nested YAML string.
func toYAML(m map[string]interface{}) (string, error) {
result, err := yaml.Marshal(m)
if err != nil {
return "", errors.Wrap(err, "toYAML")
}
return string(bytes.TrimSpace(result)), nil
}
示例4: Save
func (s *HollowStash) Save() error {
dir, filename := filepath.Split(s.InventoryFile)
f, err := ioutil.TempFile(dir, filename)
if err != nil {
return err
}
defer f.Close()
b, err := yaml.Marshal(*s)
if err != nil {
return err
}
_, err = f.Write(b)
if err != nil {
return err
}
err = os.Rename(s.InventoryFile, s.InventoryFile+".bak")
if err != nil {
return err
}
os.Rename(f.Name(), s.InventoryFile)
if err != nil {
return err
}
return nil
}
示例5: toYAML
// toYAML converts the given structure into a deeply nested YAML string.
func toYAML(m map[string]interface{}) (string, error) {
result, err := yaml.Marshal(m)
if err != nil {
return "", fmt.Errorf("toYAML: %s", err)
}
return string(bytes.TrimSpace(result)), nil
}
示例6: defaultConfigValues
/*
TODO(colhom): when we fully deprecate instanceCIDR/availabilityZone, this block of
logic will go away and be replaced by a single constant string
*/
func defaultConfigValues(t *testing.T, configYaml string) string {
defaultYaml := `
externalDNSName: test.staging.core-os.net
keyName: test-key-name
region: us-west-1
clusterName: test-cluster-name
kmsKeyArn: "arn:aws:kms:us-west-1:xxxxxxxxx:key/xxxxxxxxxxxxxxxxxxx"
`
yamlStr := defaultYaml + configYaml
c := config.Cluster{}
if err := yaml.Unmarshal([]byte(yamlStr), &c); err != nil {
t.Errorf("failed umarshalling config yaml: %v :\n%s", err, yamlStr)
}
if len(c.Subnets) > 0 {
for i := range c.Subnets {
c.Subnets[i].AvailabilityZone = fmt.Sprintf("dummy-az-%d", i)
}
} else {
//Legacy behavior
c.AvailabilityZone = "dummy-az-0"
}
out, err := yaml.Marshal(&c)
if err != nil {
t.Errorf("error marshalling cluster: %v", err)
}
return string(out)
}
示例7: 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.DefaultPaths.DataDir, 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
}
示例8: SaveAuthToken
func SaveAuthToken(configPath, authtoken string) (err error) {
// empty configuration by default for the case that we can't read it
c := new(Configuration)
// read the configuration
oldConfigBytes, err := ioutil.ReadFile(configPath)
if err == nil {
// unmarshal if we successfully read the configuration file
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
}
示例9: resultToYAML
/*
The 'getAlert' command returns a GetAlertResponse object.
The 'ResultToYaml' function is called whenever "output-format" parameter is
set to yaml.
*/
func resultToYAML(data interface{}) (string, error) {
d, err := yaml.Marshal(&data)
if err != nil {
return "", errors.New("Can not marshal the response into YAML format. " + err.Error())
}
return string(d), nil
}
示例10: 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)
}
示例11: respondError
func respondError(w http.ResponseWriter, req *http.Request, msg string, statusCode int) {
obj := make(map[string]interface{})
obj["message"] = msg
obj["type"] = "error"
obj["code"] = statusCode
switch contentType(req) {
case ContentText:
http.Error(w, msg, statusCode)
case ContentJSON:
bytes, err := json.Marshal(obj)
if err == nil {
http.Error(w, string(bytes), statusCode)
} else {
http.Error(w, "{\"type\": \"error\", \"message\": \"JSON marshal error\"}", http.StatusInternalServerError)
}
case ContentYAML:
bytes, err := yaml.Marshal(obj)
if err == nil {
http.Error(w, string(bytes), statusCode)
} else {
http.Error(w, "type: \"error\"\nmessage: \"JSON marshal error\"", http.StatusInternalServerError)
}
}
}
示例12: TestControllerLoginCommand
func (s *cmdControllerSuite) TestControllerLoginCommand(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-controller")
// Make sure that the saved server details are sufficient to connect
// to the api server.
api, err := juju.NewAPIFromName("just-a-controller", nil)
c.Assert(err, jc.ErrorIsNil)
api.Close()
}
示例13: 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)
}
}
示例14: StoreStack
func (cs *CassandraStorage) StoreStack(stack *Stack) error {
cs.lock.Lock()
defer cs.lock.Unlock()
exists, err := cs.exists(stack.Name)
if err != nil {
return err
}
if exists {
Logger.Info("Stack %s already exists", stack.Name)
return fmt.Errorf("Stack %s already exists", stack.Name)
}
if stack.From != "" {
exists, err = cs.exists(stack.From)
if !exists {
Logger.Info("Parent stack %s does not exist", stack.From)
return fmt.Errorf("Parent stack %s does not exist", stack.From)
}
}
apps, err := yaml.Marshal(stack.Applications)
if err != nil {
return err
}
query := fmt.Sprintf(`INSERT INTO %s.stacks (name, parent, applications) VALUES (?, ?, ?)`, cs.keyspace)
err = cs.connection.Query(query, stack.Name, stack.From, apps).Exec()
if err != nil {
return err
}
return nil
}
示例15: GetStackHandler
func (ts *StackDeployServer) GetStackHandler(w http.ResponseWriter, r *http.Request) {
Logger.Debug("Received get stack command")
defer r.Body.Close()
decoder := json.NewDecoder(r.Body)
getRequest := new(GetStackRequest)
decoder.Decode(&getRequest)
if getRequest.Name == "" {
http.Error(w, "Stack name required", http.StatusBadRequest)
return
} else {
stack, err := ts.storage.GetStack(getRequest.Name)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
yamlStack, err := yaml.Marshal(stack)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(yamlStack)
}
}