Esempio n. 1
0
func validAttrs(i interface{}, t string) (map[string]bool, error) {
	validAttrs := make(map[string]bool)
	tags, err := reflections.Tags(i, t)
	if err != nil {
		return nil, err
	}
	for _, v := range tags {
		validAttrs[strings.Split(v, ",")[0]] = true
	}
	return validAttrs, nil
}
func ExampleTags() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	var structTags map[string]string

	// Tags will return a field name to tag content
	// map. Nota that only field with the tag name
	// you've provided which will be matched.
	// Here structTags will contain:
	// {
	//     "FirstField": "first tag",
	//     "SecondField": "second tag",
	// }
	structTags, _ = reflections.Tags(s, "matched")
	fmt.Println(structTags)
}
Esempio n. 3
0
func getFieldByNameOrBsonTag(name string, obj interface{}) (reflect.Value, error) {
	structTags, _ := reflections.Tags(obj, "bson")

	objValue := reflectValue(obj)
	// field := objValue.FieldByName(prop)

	lname := strings.ToLower(name)

	var lk string
	for k, v := range structTags {
		lk = strings.ToLower(k)

		if lk == lname || v == name {
			field := objValue.FieldByName(k)
			return field, nil
		}
	}

	log.Fatalf("No such field: %s in obj", name)
	return objValue, errors.New("No such field")

}
Esempio n. 4
0
// Load method will try to load Environment struct
// tagged fields value from system environement. Every
// found values will override Environment field current
// value.
func (e *Environment) Load() error {
	var err error
	var envTags map[string]string

	envTags, err = reflections.Tags(*e, "env")
	if err != nil {
		return err
	}

	for field, tag := range envTags {
		envVar := os.Getenv(tag)

		if envVar != "" {
			err = reflections.SetField(e, field, envVar)
			if err != nil {
				return err
			}
		}
	}

	return nil
}