本文整理汇总了Golang中gopkg/in/yaml/v2.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)
}
}
示例2: 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)
}
}
示例3: main
func main() {
file1 := os.Args[1]
file2 := os.Args[2]
buf, err := ioutil.ReadFile(file1)
if err != nil {
panic(err)
}
m1 := make(map[interface{}]interface{})
err = goyaml.Unmarshal([]byte(buf), &m1)
if err != nil {
panic(err)
}
buf2, err := ioutil.ReadFile(file2)
if err != nil {
panic(err)
}
m2 := make(map[interface{}]interface{})
err = goyaml.Unmarshal([]byte(buf2), &m2)
if err != nil {
panic(err)
}
m3 := make(map[interface{}]interface{})
addLeftParam(m3, m1)
addRightParam(m3, m2)
ommitSameParam(m3)
//pretty.Printf("%# v\n\n", m3)
printDiffYaml(m3, "")
}
示例4: ReadConfig
func ReadConfig(path string) (*Config, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
config := Config{}
if err = yaml.Unmarshal(data, &config); err != nil {
return nil, err
}
checks := struct {
Checks map[string][]map[string]interface{} `yaml:"checks"`
Notifiers map[string]map[string]interface{} `yaml:"notify"`
}{}
if err = yaml.Unmarshal(data, &checks); err != nil {
return nil, err
}
for t, items := range checks.Checks {
switch t {
case "web":
for _, item := range items {
config.Checks = append(config.Checks, ParseWebCheck(item))
}
case "ping":
for _, item := range items {
config.Checks = append(config.Checks, ParsePingCheck(item))
}
case "dns":
for _, item := range items {
config.Checks = append(config.Checks, ParseDnsCheck(item))
}
case "port":
for _, item := range items {
config.Checks = append(config.Checks, ParsePortCheck(item))
}
default:
return nil, fmt.Errorf("Invalid check type:", t)
}
}
for t, items := range checks.Notifiers {
switch t {
case "slack":
config.Notifiers = append(config.Notifiers, ParseSlackNotifier(items))
default:
return nil, fmt.Errorf("Invalid notifier type:", t)
}
}
return &config, nil
}
示例5: TestTargetSetRecreatesTargetGroupsEveryRun
func TestTargetSetRecreatesTargetGroupsEveryRun(t *testing.T) {
verifyPresence := func(tgroups map[string]*config.TargetGroup, name string, present bool) {
if _, ok := tgroups[name]; ok != present {
msg := ""
if !present {
msg = "not "
}
t.Fatalf("'%s' should %sbe present in TargetSet.tgroups: %s", name, msg, tgroups)
}
}
cfg := &config.ServiceDiscoveryConfig{}
sOne := `
static_configs:
- targets: ["foo:9090"]
- targets: ["bar:9090"]
`
if err := yaml.Unmarshal([]byte(sOne), cfg); err != nil {
t.Fatalf("Unable to load YAML config sOne: %s", err)
}
called := make(chan struct{})
ts := NewTargetSet(&mockSyncer{
sync: func([]*config.TargetGroup) { called <- struct{}{} },
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go ts.Run(ctx)
ts.UpdateProviders(ProvidersFromConfig(*cfg))
<-called
verifyPresence(ts.tgroups, "static/0/0", true)
verifyPresence(ts.tgroups, "static/0/1", true)
sTwo := `
static_configs:
- targets: ["foo:9090"]
`
if err := yaml.Unmarshal([]byte(sTwo), cfg); err != nil {
t.Fatalf("Unable to load YAML config sTwo: %s", err)
}
ts.UpdateProviders(ProvidersFromConfig(*cfg))
<-called
verifyPresence(ts.tgroups, "static/0/0", true)
verifyPresence(ts.tgroups, "static/0/1", false)
}
示例6: mergeProject
func mergeProject(p *Project, file string, bytes []byte) (map[string]*ServiceConfig, error) {
configs := make(map[string]*ServiceConfig)
var schema rawSchema
if err := yaml.Unmarshal(bytes, &schema); err != nil {
return nil, err
}
var datas = make(rawServiceMap)
switch {
case schema.Version == "2":
datas = schema.Services
case len(schema.Version) == 0:
datas = make(rawServiceMap)
if err := yaml.Unmarshal(bytes, &datas); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("docker-compose file with schema version %q is not supported", schema.Version)
}
if err := interpolate(p.context.EnvironmentLookup, &datas); err != nil {
return nil, err
}
for name, data := range datas {
data, err := parse(p.context.ResourceLookup, p.context.EnvironmentLookup, file, data, datas)
if err != nil {
logrus.Errorf("Failed to parse service %s: %v", name, err)
return nil, err
}
if _, ok := p.Configs[name]; ok {
var rawExistingService rawService
if err := Convert(p.Configs[name], &rawExistingService); err != nil {
return nil, err
}
data = mergeConfig(rawExistingService, data)
}
datas[name] = data
}
if err := Convert(datas, &configs); err != nil {
return nil, err
}
adjustValues(configs)
return configs, nil
}
示例7: ReadConfig
func ReadConfig(conf interface{}, defaultYaml string) {
var path string = cliArgs()
err := yaml.Unmarshal([]byte(defaultYaml), conf)
if err != nil {
panic(err)
}
if path != "" {
confData := readYaml(path)
err := yaml.Unmarshal(confData, conf)
if err != nil {
panic(err)
}
}
}
示例8: TestServiceStatus
func (s *statusGetSuite) TestServiceStatus(c *gc.C) {
expected := map[string]interface{}{
"service-status": map[interface{}]interface{}{
"status-data": map[interface{}]interface{}{},
"units": map[interface{}]interface{}{
"": map[interface{}]interface{}{
"message": "this is a unit status",
"status": "active",
"status-data": map[interface{}]interface{}{},
},
},
"message": "this is a service status",
"status": "active"},
}
hctx := s.GetStatusHookContext(c)
setFakeServiceStatus(hctx)
com, err := jujuc.NewCommand(hctx, cmdString("status-get"))
c.Assert(err, jc.ErrorIsNil)
ctx := testing.Context(c)
code := cmd.Main(com, ctx, []string{"--format", "json", "--include-data", "--service"})
c.Assert(code, gc.Equals, 0)
var out map[string]interface{}
c.Assert(goyaml.Unmarshal(bufferBytes(ctx.Stdout), &out), gc.IsNil)
c.Assert(out, gc.DeepEquals, expected)
}
示例9: 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)
}
示例10: setFromFileByPrefix
func setFromFileByPrefix(prefix, fn string, ret map[string]string) {
p := path.Ext(fn)
_, err := os.Stat(fn)
if err != nil {
return
}
file, err := os.Open(fn)
if err != nil {
log.Printf("Could not open flagconf file '%s': %s", fn, err)
return
}
log.Printf("Loading config file: %s", fn)
by, err := ioutil.ReadAll(file)
if err != nil {
goto out
}
switch p {
case ".json":
err = json.Unmarshal(by, &ret)
default: // assume yaml
err = yaml.Unmarshal(by, &ret)
}
out:
if err != nil {
log.Printf("flagconf (prefix: %s, suffix: %s): %s", prefix, p, err)
}
}
示例11: ClusterFromBytes
// ClusterFromBytes Necessary for unit tests, which store configs as hardcoded strings
func ClusterFromBytes(data []byte) (*Cluster, error) {
c := newDefaultCluster()
if err := yaml.Unmarshal(data, c); err != nil {
return nil, fmt.Errorf("failed to parse cluster: %v", err)
}
// HostedZone needs to end with a '.', amazon will not append it for you.
// as it will with RecordSets
c.HostedZone = WithTrailingDot(c.HostedZone)
// If the user specified no subnets, we assume that a single AZ configuration with the default instanceCIDR is demanded
if len(c.Subnets) == 0 && c.InstanceCIDR == "" {
c.InstanceCIDR = "10.0.0.0/24"
}
c.HostedZoneID = withHostedZoneIDPrefix(c.HostedZoneID)
if err := c.valid(); err != nil {
return nil, fmt.Errorf("invalid cluster: %v", err)
}
// For backward-compatibility
if len(c.Subnets) == 0 {
c.Subnets = []Subnet{
{
AvailabilityZone: c.AvailabilityZone,
InstanceCIDR: c.InstanceCIDR,
},
}
}
return c, nil
}
示例12: LoadFromBytes
// LoadFromBytes loads a configuration from a bytes slice
func LoadFromBytes(data []byte) (*Config, error) {
config := NewConfig()
if err := yaml.Unmarshal(data, config); err != nil {
return nil, err
}
return config, nil
}
示例13: GetUnderlyingFederatedContexts
func (f *Framework) GetUnderlyingFederatedContexts() []E2EContext {
kubeconfig := framework.KubeConfig{}
configBytes, err := ioutil.ReadFile(framework.TestContext.KubeConfig)
framework.ExpectNoError(err)
err = yaml.Unmarshal(configBytes, &kubeconfig)
framework.ExpectNoError(err)
e2eContexts := []E2EContext{}
for _, context := range kubeconfig.Contexts {
if strings.HasPrefix(context.Name, "federation") && context.Name != framework.TestContext.FederatedKubeContext {
user := kubeconfig.FindUser(context.Context.User)
if user == nil {
framework.Failf("Could not find user for context %+v", context)
}
cluster := kubeconfig.FindCluster(context.Context.Cluster)
if cluster == nil {
framework.Failf("Could not find cluster for context %+v", context)
}
dnsSubdomainName, err := GetValidDNSSubdomainName(context.Name)
if err != nil {
framework.Failf("Could not convert context name %s to a valid dns subdomain name, error: %s", context.Name, err)
}
e2eContexts = append(e2eContexts, E2EContext{
RawName: context.Name,
Name: dnsSubdomainName,
Cluster: cluster,
User: user,
})
}
}
return e2eContexts
}
示例14: 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("model %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.ModelUUID
info.serverUUID = values.ServerUUID
info.caCert = values.CACert
info.apiEndpoints = values.Controllers
info.apiHostnames = values.ServerHostnames
info.bootstrapConfig = values.Config
info.source = sourceJenv
return &info, nil
}
示例15: 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
}