Пример #1
0
func (f *defaultFormats) Parse(name, data string) (interface{}, error) {
	f.Lock()
	defer f.Unlock()
	nme := f.normalizeName(name)
	for _, v := range f.data {
		if v.Name == nme {
			nw := reflect.New(v.Type).Interface()
			if dec, ok := nw.(encoding.TextUnmarshaler); ok {
				if err := dec.UnmarshalText([]byte(data)); err != nil {
					return nil, err
				}
				return nw, nil
			}
			return nil, errors.InvalidTypeName(name)
		}
	}
	return nil, errors.InvalidTypeName(name)
}
Пример #2
0
// FormatOf validates if a string matches a format in the format registry
func FormatOf(path, in, format, data string, registry strfmt.Registry) *errors.Validation {
	if registry == nil {
		registry = strfmt.Default
	}
	if ok := registry.ContainsName(format); !ok {
		return errors.InvalidTypeName(format)
	}
	if ok := registry.Validates(format, data); !ok {
		return errors.InvalidType(path, in, format, data)
	}

	return nil
}
Пример #3
0
// MapStructureHookFunc is a decode hook function for mapstructure
func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc {
	return func(from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) {
		if from.Kind() != reflect.String {
			return data, nil
		}
		for _, v := range f.data {
			tpe, _ := f.GetType(v.Name)
			if to == tpe {
				switch v.Name {
				case "date":
					d, err := time.Parse(RFC3339FullDate, data.(string))
					if err != nil {
						return nil, err
					}
					return Date(d), nil
				case "datetime":
					return ParseDateTime(data.(string))
				case "duration":
					dur, err := ParseDuration(data.(string))
					if err != nil {
						return nil, err
					}
					return Duration(dur), nil
				case "uri":
					return URI(data.(string)), nil
				case "email":
					return Email(data.(string)), nil
				case "uuid":
					return UUID(data.(string)), nil
				case "uuid3":
					return UUID3(data.(string)), nil
				case "uuid4":
					return UUID4(data.(string)), nil
				case "uuid5":
					return UUID5(data.(string)), nil
				case "hostname":
					return Hostname(data.(string)), nil
				case "ipv4":
					return IPv4(data.(string)), nil
				case "ipv6":
					return IPv6(data.(string)), nil
				case "mac":
					return MAC(data.(string)), nil
				case "isbn":
					return ISBN(data.(string)), nil
				case "isbn10":
					return ISBN10(data.(string)), nil
				case "isbn13":
					return ISBN13(data.(string)), nil
				case "creditcard":
					return CreditCard(data.(string)), nil
				case "ssn":
					return SSN(data.(string)), nil
				case "hexcolor":
					return HexColor(data.(string)), nil
				case "rgbcolor":
					return RGBColor(data.(string)), nil
				case "byte":
					return Base64(data.(string)), nil
				case "password":
					return Password(data.(string)), nil
				default:
					return nil, errors.InvalidTypeName(v.Name)

				}
			}
		}
		return data, nil
	}
}