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


Golang mapstructure.Decode函數代碼示例

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


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

示例1: document

func (intermediate *intermediateAwsPolicyDocument) document() (*awsPolicyDocument, error) {
	var statements []*awsPolicyStatement

	switch s := intermediate.Statements.(type) {
	case []interface{}:
		if err := mapstructure.Decode(s, &statements); err != nil {
			return nil, errwrap.Wrapf("Error parsing statement: {{err}}", err)
		}
	case map[string]interface{}:
		var singleStatement *awsPolicyStatement
		if err := mapstructure.Decode(s, &singleStatement); err != nil {
			return nil, errwrap.Wrapf("Error parsing statement: {{err}}", err)
		}
		statements = append(statements, singleStatement)
	default:
		return nil, errors.New("Unknown error parsing statement")
	}

	document := &awsPolicyDocument{
		Version:    intermediate.Version,
		Id:         intermediate.Id,
		Statements: statements,
	}

	return document, nil
}
開發者ID:hashicorp,項目名稱:terraform,代碼行數:26,代碼來源:aws_policy_equivalence.go

示例2: mapDecode

func mapDecode(o *Order, customProvider OrderCustomProvider) (order *Order, err error) {
	/* Map OrderCustom */
	orderCustom := customProvider.NewOrderCustom()
	if orderCustom != nil && o.Custom != nil {
		err = mapstructure.Decode(o.Custom, orderCustom)
		if err != nil {
			return nil, err
		}
		o.Custom = orderCustom
	}

	/* Map PostionCustom */
	for _, position := range o.Positions {
		positionCustom := customProvider.NewPositionCustom()
		if positionCustom != nil && position.Custom != nil {

			err = mapstructure.Decode(position.Custom, positionCustom)
			if err != nil {
				return nil, err
			}
			position.Custom = positionCustom
		}
	}
	return o, nil
}
開發者ID:foomo,項目名稱:shop,代碼行數:25,代碼來源:persistor.go

示例3: Handle

func (h *GenericHandler) Handle(event model.WatchEvent) error {

	if i, ok := event.Object.(map[string]interface{}); ok {
		var metadata *model.ObjectMeta
		var kind string
		var selector map[string]interface{}
		if h.kindHandled == RCKind {
			var rc model.ReplicationController
			mapstructure.Decode(i, &rc)
			if rc == (model.ReplicationController{}) || rc.Spec == nil {
				log.Infof("Couldn't decode %+v to rc.", i)
				return nil
			}
			kind = rc.Kind
			selector = rc.Spec.Selector
			metadata = rc.Metadata
		} else if h.kindHandled == ServiceKind {
			var svc model.Service
			mapstructure.Decode(i, &svc)
			if svc == (model.Service{}) || svc.Spec == nil {
				log.Infof("Couldn't decode %+v to service.", i)
				return nil
			}
			kind = svc.Kind
			selector = svc.Spec.Selector
			metadata = svc.Metadata
		} else {
			return fmt.Errorf("Unrecognized handled kind [%s].", h.kindHandled)
		}

		serviceEvent := &client.ExternalServiceEvent{
			ExternalId: metadata.Uid,
			EventType:  constructEventType(event),
		}

		switch event.Type {
		case "MODIFIED":
			fallthrough

		case "ADDED":
			err := h.add(selector, metadata, event, serviceEvent, constructResourceType(kind))
			if err != nil {
				return err
			}

		case "DELETED":
			service := client.Service{
				Kind: constructResourceType(kind),
			}
			serviceEvent.Service = service
		default:
			return nil
		}

		_, err := h.rancherClient.ExternalServiceEvent.Create(serviceEvent)
		return err

	}
	return fmt.Errorf("Couldn't decode event [%#v]", event)
}
開發者ID:alena1108,項目名稱:kubernetes-agent,代碼行數:60,代碼來源:generic_handler.go

示例4: New

func New(credential, builder map[string]interface{}) (*DigitalOcean, error) {
	d := DigitalOcean{}

	// Credentials
	if err := mapstructure.Decode(credential, &d.Creds); err != nil {
		return nil, err
	}

	// Builder data
	if err := mapstructure.Decode(builder, &d.Builder); err != nil {
		return nil, err
	}

	if d.Creds.ClientID == "" {
		return nil, errors.New("credentials client_id is empty")
	}

	if d.Creds.APIKey == "" {
		return nil, errors.New("credentials api_key is empty")
	}

	d.Builder.ClientID = d.Creds.ClientID
	d.Builder.APIKey = d.Creds.APIKey

	d.Client = digitalocean.DigitalOceanClient{}.New(d.Creds.ClientID, d.Creds.APIKey)

	// authenticate credentials with a simple call
	_, err := d.Regions()
	if err != nil {
		return nil, errors.New("authentication with DigitalOcean failed.")
	}

	return &d, nil
}
開發者ID:koding,項目名稱:koding,代碼行數:34,代碼來源:digitalocean.go

示例5: handleChangeNotification

func handleChangeNotification(socket *websocket.Conn, userID string, err chan string) {
	res, errr := r.Table("notifications").
		Filter(r.Row.Field("UserId").
			Eq(userID)).
		Changes().
		Run(api.Sess)

	var value HandleChange
	if errr != nil {
		err <- errr.Error()
	}
	for res.Next(&value) {
		var notif api.Notification
		var simpleNotif api.WebSocketNotification

		mapstructure.Decode(value.NewVal, &notif)
		if notif.Id == "" {
			mapstructure.Decode(value.OldVal, &notif)
			simpleNotif.OldVal = true
		} else {
			simpleNotif.OldVal = false
		}
		simpleNotif.Title = "notification"
		simpleNotif.Type = notif.Type
		simpleNotif.Name = notif.Name
		simpleNotif.UserIdFrom = notif.UserIdFrom
		simpleNotif.IdLink = notif.IdLink
		simpleNotif.CreatedAt = notif.CreatedAt
		errr := socket.WriteJSON(simpleNotif)
		if errr != nil {
			err <- errr.Error()
		}
	}
}
開發者ID:Fantasim,項目名稱:Langage-Go,代碼行數:34,代碼來源:websockets.go

示例6: parseConfigMap

// Parses YAML structure to typed list of Hops
func parseConfigMap(configMap map[string]interface{}) (hops, error) {
	if err := validateConfig(configMap); err != nil {
		return nil, err
	}

	hopsConfig := make(hops)
	rh := make(rawHops)
	err := mapstructure.Decode(configMap, &rh)
	if err != nil {
		panic(err)
	}

	for name, defs := range rh {
		for _, def := range defs {
			if dockMap, ok := def["docker"]; ok {
				docker := Docker{}
				err := mapstructure.Decode(dockMap, &docker)
				if err != nil {
					panic(err)
				}
				hopsConfig[name] = []Hop{&docker}
			} else {
				return nil, fmt.Errorf(
					"There's no definition of docker for %v", name)
			}
		}
	}
	return hopsConfig, nil
}
開發者ID:kamilchm,項目名稱:hopper,代碼行數:30,代碼來源:config.go

示例7: Less

func (sd *sortableDistroByNumStaticHost) Less(i, j int) bool {
	if sd.distros[i].Provider != evergreen.HostTypeStatic &&
		sd.distros[j].Provider != evergreen.HostTypeStatic {
		return false
	}
	if sd.distros[i].Provider == evergreen.HostTypeStatic &&
		sd.distros[j].Provider != evergreen.HostTypeStatic {
		return true
	}
	if sd.distros[i].Provider != evergreen.HostTypeStatic &&
		sd.distros[j].Provider == evergreen.HostTypeStatic {
		return false
	}

	h1 := &static.Settings{}
	h2 := &static.Settings{}

	err := mapstructure.Decode(sd.distros[i].ProviderSettings, h1)
	if err != nil {
		return false
	}

	err = mapstructure.Decode(sd.distros[j].ProviderSettings, h2)
	if err != nil {
		return false
	}

	return len(h1.Hosts) > len(h2.Hosts)
}
開發者ID:himanshugpt,項目名稱:evergreen,代碼行數:29,代碼來源:duration_based_host_allocator.go

示例8: Configure

func (p *PostProcessor) Configure(raws ...interface{}) error {
	// Store the raw configs for usage later
	p.rawConfigs = raws

	for _, raw := range raws {
		err := mapstructure.Decode(raw, &p.config)
		if err != nil {
			return err
		}
	}

	ppExtraConfig := make(map[string]interface{})
	if p.config.OutputPath == "" {
		p.config.OutputPath = "packer_{{ .BuildName }}_{{.Provider}}.box"
		ppExtraConfig["output"] = p.config.OutputPath
	}

	_, err := template.New("output").Parse(p.config.OutputPath)
	if err != nil {
		return fmt.Errorf("output invalid template: %s", err)
	}

	// Store the extra configuration for post-processors
	p.rawConfigs = append(p.rawConfigs, ppExtraConfig)

	// TODO(mitchellh): Properly handle multiple raw configs
	var mapConfig map[string]interface{}
	if err := mapstructure.Decode(raws[0], &mapConfig); err != nil {
		return err
	}

	p.premade = make(map[string]packer.PostProcessor)
	errors := make([]error, 0)
	for k, raw := range mapConfig {
		pp := keyToPostProcessor(k)
		if pp == nil {
			continue
		}

		// Create the proper list of configurations
		ppConfigs := make([]interface{}, 0, len(p.rawConfigs)+1)
		copy(ppConfigs, p.rawConfigs)
		ppConfigs = append(ppConfigs, raw)

		if err := pp.Configure(ppConfigs...); err != nil {
			errors = append(errors, err)
		}

		p.premade[k] = pp
	}

	if len(errors) > 0 {
		return &packer.MultiError{errors}
	}

	return nil
}
開發者ID:phobos182,項目名稱:packer,代碼行數:57,代碼來源:post-processor.go

示例9: Handle

func (h *GenericHandler) Handle(event model.WatchEvent) error {

	if i, ok := event.Object.(map[string]interface{}); ok {
		var metadata *model.ObjectMeta
		var kind string
		var selector map[string]interface{}
		if h.kindHandled == RCKind {
			var rc model.ReplicationController
			mapstructure.Decode(i, &rc)
			kind = rc.Kind
			selector = rc.Spec.Selector
			metadata = rc.Metadata
		} else if h.kindHandled == ServiceKind {
			var svc model.Service
			mapstructure.Decode(i, &svc)
			kind = svc.Kind
			selector = svc.Spec.Selector
			metadata = svc.Metadata
		} else {
			return fmt.Errorf("Unrecognized handled kind [%s].", h.kindHandled)
		}

		ts, err := time.Parse(time.RFC3339, metadata.CreationTimestamp)
		if err != nil {
			return err
		}

		serviceEvent := &client.ServiceEvent{
			Name:              metadata.Name,
			ExternalId:        metadata.Uid,
			EventType:         constructEventType(event),
			ResourceType:      constructResourceType(kind),
			ExternalTimestamp: ts.Unix(),
		}

		switch event.Type {
		case "MODIFIED":
			fallthrough

		case "ADDED":
			err = h.add(selector, metadata, event, serviceEvent, serviceEvent.ResourceType)
			if err != nil {
				return err
			}

		case "DELETED":
			// No extra fields required for delete
		default:
			return nil
		}

		_, err = h.rancherClient.ServiceEvent.Create(serviceEvent)
		return err

	}
	return fmt.Errorf("Couldn't decode event [%#v]", event)
}
開發者ID:cjellick,項目名稱:kubernetes-agent,代碼行數:57,代碼來源:generic_handler.go

示例10: LoadBlocks

// LoadBlocks will load the blocks that are stored in the raw_blocks data and
// mix it up with the user input that we give it.
func (t *JsonTemplate) LoadBlocks(user_input interface{}) {
	var blocks []map[string]interface{}
	var input map[string]interface{}
	mapstructure.Decode(t.raw_block_data, &blocks)
	mapstructure.Decode(user_input, &input)

	for _, block := range blocks {
		t.blocks = append(t.blocks, t.LoadBlock(block, input))
	}

	t.wg.Wait()
}
開發者ID:jelmersnoeck,項目名稱:dogen,代碼行數:14,代碼來源:json_template.go

示例11: Start

func Start(orientChan chan orient.Event, shootChan chan shoot.Event) {
	port := 4242

	var upgrader = websocket.Upgrader{
		ReadBufferSize:  2048,
		WriteBufferSize: 2048,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	http.HandleFunc("/control", func(w http.ResponseWriter, r *http.Request) {
		log.Debug("Connection received")
		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Fatal(err)
		}

		defer conn.Close()

		for {
			messageType, reader, err := conn.NextReader()
			if err != nil {
				log.Println(err)
				return
			}
			if messageType == websocket.TextMessage {
				packet := Packet{}
				decoder := json.NewDecoder(reader)
				if err := decoder.Decode(&packet); err != nil {
					log.Warning(err)
					continue
				}

				switch packet.Type {
				case "orient":
					event := orient.Event{}
					mapstructure.Decode(packet.Payload, &event)
					orientChan <- event
				case "shoot":
					event := shoot.Event{}
					mapstructure.Decode(packet.Payload, &event)
					shootChan <- event
				default:
					log.Info("Oops unknown packet: ", packet)
				}
			}
		}
	})

	go http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil)
	log.Infof("Websocket server started on port %d", port)
}
開發者ID:HackerLoop,項目名稱:goNerfTurret,代碼行數:53,代碼來源:control.go

示例12: testCredsWrite

func testCredsWrite(t *testing.T, roleName string, data map[string]interface{}, expectError bool) logicaltest.TestStep {
	return logicaltest.TestStep{
		Operation: logical.WriteOperation,
		Path:      fmt.Sprintf("creds/%s", roleName),
		Data:      data,
		ErrorOk:   true,
		Check: func(resp *logical.Response) error {
			if resp == nil {
				return fmt.Errorf("response is nil")
			}
			if resp.Data == nil {
				return fmt.Errorf("data is nil")
			}
			if expectError {
				var e struct {
					Error string `mapstructure:"error"`
				}
				if err := mapstructure.Decode(resp.Data, &e); err != nil {
					return err
				}
				if len(e.Error) == 0 {
					return fmt.Errorf("expected error, but write succeeded.")
				}
				return nil
			}
			if roleName == testDynamicRoleName {
				var d struct {
					Key string `mapstructure:"key"`
				}
				if err := mapstructure.Decode(resp.Data, &d); err != nil {
					return err
				}
				if d.Key == "" {
					return fmt.Errorf("Generated key is an empty string")
				}
				// Checking only for a parsable key
				_, err := ssh.ParsePrivateKey([]byte(d.Key))
				if err != nil {
					return fmt.Errorf("Generated key is invalid")
				}
			} else {
				if resp.Data["key_type"] != KeyTypeOTP {
					return fmt.Errorf("Incorrect key_type")
				}
				if resp.Data["key"] == nil {
					return fmt.Errorf("Invalid key")
				}
			}
			return nil
		},
	}
}
開發者ID:rlhatcher,項目名稱:vault,代碼行數:52,代碼來源:backend_test.go

示例13: APISave

// APISave returns true if the file is local only
func (parser *Parser) APISave(payloads []*get3w.SavePayload) error {
	for _, payload := range payloads {
		switch payload.Type {
		case get3w.PayloadTypeConfig:
			if payload.Status == get3w.PayloadStatusModified || payload.Status == get3w.PayloadStatusAdded {
				var config get3w.Config
				if err := mapstructure.Decode(payload.Data, &config); err != nil {
					return err
				}
				parser.Config = &config
				if err := parser.WriteConfig(); err != nil {
					return err
				}
			}

		case get3w.PayloadTypePage:
			if payload.Status == get3w.PayloadStatusModified || payload.Status == get3w.PayloadStatusAdded {
				var page get3w.Page
				if err := mapstructure.Decode(payload.Data, &page); err != nil {
					return err
				}
				if err := parser.WritePage(&page); err != nil {
					return err
				}
			}

		case get3w.PayloadTypeSection:
			if payload.Status == get3w.PayloadStatusModified || payload.Status == get3w.PayloadStatusAdded {
				var section get3w.Section
				if err := mapstructure.Decode(payload.Data, &section); err != nil {
					return err
				}
				if err := parser.saveSection(&section); err != nil {
					return err
				}
			} else if payload.Status == get3w.PayloadStatusRemoved {
				var section get3w.Section
				if err := mapstructure.Decode(payload.Data, &section); err != nil {
					return err
				}
				if err := parser.deleteSection(section.Path); err != nil {
					return err
				}
			}

		}
	}
	return nil
}
開發者ID:get3w,項目名稱:get3w,代碼行數:50,代碼來源:api.go

示例14: UnmarshalJSON

func (s *SourceOptionsSlice) UnmarshalJSON(data []byte) error {
	var maps []map[string]interface{}

	err := json.Unmarshal(data, &maps)
	if err != nil {
		return bosherr.WrapError(err, "Unmarshalling sources")
	}

	for _, m := range maps {
		if optType, ok := m["Type"]; ok {
			var err error
			var opts SourceOptions

			switch {
			case optType == "HTTP":
				var o HTTPSourceOptions
				err, opts = mapstruc.Decode(m, &o), o

			case optType == "InstanceMetadata":
				var o InstanceMetadataSourceOptions
				err, opts = mapstruc.Decode(m, &o), o

			case optType == "ConfigDrive":
				var o ConfigDriveSourceOptions
				err, opts = mapstruc.Decode(m, &o), o

			case optType == "File":
				var o FileSourceOptions
				err, opts = mapstruc.Decode(m, &o), o

			case optType == "CDROM":
				var o CDROMSourceOptions
				err, opts = mapstruc.Decode(m, &o), o

			default:
				err = bosherr.Errorf("Unknown source type '%s'", optType)
			}

			if err != nil {
				return bosherr.WrapErrorf(err, "Unmarshalling source type '%s'", optType)
			}
			*s = append(*s, opts)
		} else {
			return bosherr.Error("Missing source type")
		}
	}

	return nil
}
開發者ID:jianqiu,項目名稱:bosh-agent,代碼行數:49,代碼來源:settings_source_factory.go

示例15: marshal

// marshal merges config a and b and decodes the merge config into the provided
// structure.
func marshal(a Config, b Config, rawVal interface{}) (err error) {
	err = mapstructure.Decode(&a, rawVal)
	if err != nil {
		return
	}

	if b != nil {
		err = mapstructure.Decode(&b, rawVal)
		if err != nil {
			return
		}
	}

	return
}
開發者ID:hypebeast,項目名稱:go-config,代碼行數:17,代碼來源:config.go


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