本文整理匯總了Golang中github.com/mitchellh/mapstructure.NewDecoder函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewDecoder函數的具體用法?Golang NewDecoder怎麽用?Golang NewDecoder使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewDecoder函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ParseRequestParameter
// ParseRequestParameter applies parameters of request from body and query.
func (c RootController) ParseRequestParameter(p parameters.RequestParameter) error {
req := c.GetContext().Request()
// Request Body
if b := req.Body(); len(b) > 0 {
if err := json.Unmarshal(b, p); err != nil {
return err
}
}
// Request Query
query := map[string]interface{}{}
// Modify query into parsable one
for k, v := range req.Query() {
if strings.HasSuffix(k, "[]") {
// e.g.) foo[]=[]string => foo=[]string
query[k[:len(k)-2]] = v
} else {
// e.g.) foo=[]string => foo=string
query[k] = v[0]
}
}
mapcfg := &mapstructure.DecoderConfig{
WeaklyTypedInput: true,
Result: p,
}
decoder, err := mapstructure.NewDecoder(mapcfg)
if err != nil {
return err
}
if err = decoder.Decode(query); err != nil {
return err
}
return nil
}
示例2: CreateParamList
// CreateParamList tries to match a CBOR-RPC parameter list to a specific
// callable's parameter list. funcv is the reflected method to eventually
// call, and params is the list of parameters from the CBOR-RPC request.
// On success, the return value is a list of parameter values that can be
// passed to funcv.Call().
func CreateParamList(funcv reflect.Value, params []interface{}) ([]reflect.Value, error) {
funct := funcv.Type()
numParams := funct.NumIn()
if len(params) != numParams {
return nil, errors.New("wrong number of parameters")
}
results := make([]reflect.Value, numParams)
for i := 0; i < numParams; i++ {
paramType := funct.In(i)
paramValue := reflect.New(paramType)
param := paramValue.Interface()
config := mapstructure.DecoderConfig{
DecodeHook: DecodeBytesAsString,
Result: param,
}
decoder, err := mapstructure.NewDecoder(&config)
if err != nil {
return nil, err
}
err = decoder.Decode(params[i])
if err != nil {
return nil, err
}
results[i] = paramValue.Elem()
}
return results, nil
}
示例3: saveConfigRequestUnmarshaler
func saveConfigRequestUnmarshaler(r *http.Request) (atc.Config, db.PipelinePausedState, error) {
var configStructure interface{}
pausedState, err := requestToConfig(r.Header.Get("Content-Type"), r.Body, &configStructure)
if err != nil {
return atc.Config{}, db.PipelineNoChange, err
}
var config atc.Config
var md mapstructure.Metadata
msConfig := &mapstructure.DecoderConfig{
Metadata: &md,
Result: &config,
WeaklyTypedInput: true,
DecodeHook: atc.SanitizeDecodeHook,
}
decoder, err := mapstructure.NewDecoder(msConfig)
if err != nil {
return atc.Config{}, db.PipelineNoChange, ErrFailedToConstructDecoder
}
if err := decoder.Decode(configStructure); err != nil {
return atc.Config{}, db.PipelineNoChange, ErrCouldNotDecode
}
if len(md.Unused) != 0 {
return atc.Config{}, db.PipelineNoChange, ExtraKeysError{extraKeys: md.Unused}
}
return config, pausedState, nil
}
示例4: decodeConfig
func (r *ResourceProvisioner) decodeConfig(c *terraform.ResourceConfig) (*Provisioner, error) {
// decodes configuration from terraform and builds out a provisioner
p := new(Provisioner)
decoderConfig := &mapstructure.DecoderConfig{
ErrorUnused: true,
WeaklyTypedInput: true,
Result: p,
}
decoder, err := mapstructure.NewDecoder(decoderConfig)
if err != nil {
return nil, err
}
// build a map of all configuration values, by default this is going to
// pass in all configuration elements for the base configuration as
// well as extra values. Build a single value and then from there, continue forth!
m := make(map[string]interface{})
for k, v := range c.Raw {
m[k] = v
}
for k, v := range c.Config {
m[k] = v
}
err = decoder.Decode(m)
if err != nil {
return nil, err
}
return p, nil
}
示例5: parseTokenData
func parseTokenData(data string, into interface{}) (err error) {
m := make(map[string]string)
tuples := strings.Split(strings.TrimSpace(data), " ")
for _, tuple := range tuples {
keyValue := strings.SplitN(tuple, ":", 2)
if len(keyValue) != 2 {
err = errors.New("Malformed token data")
return
}
m[keyValue[0]] = keyValue[1]
}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Metadata: nil,
Result: into,
WeaklyTypedInput: true,
})
if err != nil {
return
}
return decoder.Decode(m)
}
示例6: Decode
// Decode from object to data structure using `mapstructure`
func Decode(obj ast.Node, excludeKeys []string, defaultValues map[string]interface{}, data interface{}) error {
var m map[string]interface{}
if err := hcl.DecodeObject(&m, obj); err != nil {
return maskAny(err)
}
for _, key := range excludeKeys {
delete(m, key)
}
for k, v := range defaultValues {
if _, ok := m[k]; !ok {
m[k] = v
}
}
decoderConfig := &mapstructure.DecoderConfig{
ErrorUnused: true,
WeaklyTypedInput: true,
Metadata: nil,
Result: data,
}
decoder, err := mapstructure.NewDecoder(decoderConfig)
if err != nil {
return maskAny(err)
}
return maskAny(decoder.Decode(m))
}
示例7: parseUpdate
func parseUpdate(result *structs.UpdateStrategy, list *ast.ObjectList) error {
list = list.Elem()
if len(list.Items) > 1 {
return fmt.Errorf("only one 'update' block allowed per job")
}
// Get our resource object
o := list.Items[0]
var m map[string]interface{}
if err := hcl.DecodeObject(&m, o.Val); err != nil {
return err
}
// Check for invalid keys
valid := []string{
"stagger",
"max_parallel",
}
if err := checkHCLKeys(o.Val, valid); err != nil {
return err
}
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
WeaklyTypedInput: true,
Result: result,
})
if err != nil {
return err
}
return dec.Decode(m)
}
示例8: parseRestartPolicy
func parseRestartPolicy(final **structs.RestartPolicy, list *ast.ObjectList) error {
list = list.Elem()
if len(list.Items) > 1 {
return fmt.Errorf("only one 'restart' block allowed")
}
// Get our job object
obj := list.Items[0]
var m map[string]interface{}
if err := hcl.DecodeObject(&m, obj.Val); err != nil {
return err
}
var result structs.RestartPolicy
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
WeaklyTypedInput: true,
Result: &result,
})
if err != nil {
return err
}
if err := dec.Decode(m); err != nil {
return err
}
*final = &result
return nil
}
示例9: GetSource
// GetSource resolves source from a map.
// Source must contain at least one property with name "type", which will be
// used to select proper source implementation.
func GetSource(rawSource map[string]interface{}) (Source, error) {
sourceType, found := configMappings[rawSource["type"].(string)]
if !found {
return nil, fmt.Errorf("Failed to find source type: %s", rawSource["type"])
}
delete(rawSource, "type")
var metadata mapstructure.Metadata
loader := reflect.New(sourceType).Interface().(Source)
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Metadata: &metadata,
Result: loader,
})
if err != nil {
return nil, err
}
if err := decoder.Decode(rawSource); err != nil {
return nil, err
}
if len(metadata.Unused) > 0 {
return nil, fmt.Errorf("unknown configuration keys: %v", metadata.Unused)
}
return loader, nil
}
示例10: DecodeConfig
// DecodeConfig reads the configuration from the given reader in JSON
// format and decodes it into a proper Config structure.
func DecodeConfig(r io.Reader) (*Config, error) {
var raw interface{}
dec := json.NewDecoder(r)
if err := dec.Decode(&raw); err != nil {
return nil, err
}
// Decode
var md mapstructure.Metadata
var result Config
msdec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Metadata: &md,
Result: &result,
})
if err != nil {
return nil, err
}
if err := msdec.Decode(raw); err != nil {
return nil, err
}
// If we never set the protocol, then set it to the default
if !containsKey(md.Keys, "protocol") {
result.Protocol = DefaultConfig.Protocol
}
return &result, nil
}
示例11: NewTimetail
func NewTimetail(cfg map[string]interface{}) (t parsing.Fetcher, err error) {
var (
config TimetailConfig
decoder_config = mapstructure.DecoderConfig{
// To allow decoder parses []uint8 as string
WeaklyTypedInput: true,
Result: &config,
}
)
decoder, err := mapstructure.NewDecoder(&decoder_config)
if err != nil {
return nil, err
}
err = decoder.Decode(cfg)
if err != nil {
return nil, err
}
if config.ConnTimeout <= 0 {
config.ConnTimeout = CONNECTION_TIMEOUT
}
if config.ReadTimeout <= 0 {
config.ReadTimeout = RW_TIMEOUT
}
t = &Timetail{
TimetailConfig: config,
}
return
}
示例12: decode
// A wrapper around mapstructure.Decode that mimics the WeakDecode functionality
func decode(input interface{}, config *mapstructure.DecoderConfig) error {
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
}
示例13: Extract
// Extract interprets any serverResult as a Server, if possible.
func (r serverResult) Extract() (*Server, error) {
if r.Err != nil {
return nil, r.Err
}
var response struct {
Server Server `mapstructure:"server"`
}
config := &mapstructure.DecoderConfig{
DecodeHook: toMapFromString,
Result: &response,
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return nil, err
}
err = decoder.Decode(r.Body)
if err != nil {
return nil, err
}
return &response.Server, nil
}
示例14: ParseSSHConfig
// ParseSSHConfig is used to convert the ConnInfo of the ResourceState into
// a SSHConfig struct
func ParseSSHConfig(s *terraform.ResourceState) (*SSHConfig, error) {
sshConf := &SSHConfig{}
decConf := &mapstructure.DecoderConfig{
WeaklyTypedInput: true,
Result: sshConf,
}
dec, err := mapstructure.NewDecoder(decConf)
if err != nil {
return nil, err
}
if err := dec.Decode(s.ConnInfo); err != nil {
return nil, err
}
if sshConf.User == "" {
sshConf.User = DefaultUser
}
if sshConf.Port == 0 {
sshConf.Port = DefaultPort
}
if sshConf.ScriptPath == "" {
sshConf.ScriptPath = DefaultScriptPath
}
if sshConf.Timeout != "" {
sshConf.TimeoutVal = safeDuration(sshConf.Timeout, DefaultTimeout)
} else {
sshConf.TimeoutVal = DefaultTimeout
}
return sshConf, nil
}
示例15: ConvertValue
// ConvertValue converts input (e.g. a map[string]interface{}) to an instance of inputType.
func ConvertValue(inputType reflect.Type, input interface{}, customUnpack bool, baseConfig *DecoderConfig, defaultTagName string) (output reflect.Value, err error) {
output = reflect.New(inputType)
parameters := output.Interface()
if customUnpack {
if err := parameters.(Unpacker).Unpack(input); err != nil {
return reflect.ValueOf(nil), fmt.Errorf("Failed to convert parameters to type %v: %s", inputType, err)
}
} else {
var config *mapstructure.DecoderConfig
if baseConfig != nil {
config = &mapstructure.DecoderConfig{
Result: parameters,
TagName: baseConfig.TagName,
ErrorUnused: baseConfig.ErrorUnused,
ZeroFields: baseConfig.ZeroFields,
WeaklyTypedInput: baseConfig.WeaklyTypedInput,
DecodeHook: baseConfig.DecodeHook,
}
} else {
config = &mapstructure.DecoderConfig{
Metadata: nil,
Result: parameters,
TagName: defaultTagName,
}
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return reflect.ValueOf(nil), fmt.Errorf("Failed to construct decoder: %s", err)
}
if err = decoder.Decode(input); err != nil {
return reflect.ValueOf(nil), fmt.Errorf("Failed to convert parameters to type %v: %s", inputType, err)
}
}
return
}