Last active
August 19, 2017 11:14
-
-
Save josephspurrier/c8f81a6ba64603aa913097e83b32dce3 to your computer and use it in GitHub Desktop.
Get Struct Tag in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func Tag(s interface{}, name string) (reflect.StructTag, error) { | |
var tag reflect.StructTag | |
t := reflect.TypeOf(s) | |
// Prevent running on types other than struct | |
if t.Kind() != reflect.Struct { | |
return "", errors.New(fmt.Sprintf("%v is not a struct\n", t.Name())) | |
} | |
/* | |
// Prevent running on types other than struct | |
if reflect.TypeOf(model).Kind() != reflect.Ptr { | |
return ErrNotStruct, ErrNotStruct.Error() | |
} else if reflect.TypeOf(model).Elem().Kind() != reflect.Struct { | |
return ErrNotStruct, ErrNotStruct.Error() | |
} | |
*/ | |
field, ok := reflect.TypeOf(s).FieldByName(name) | |
if !ok { | |
return tag, errors.New("Field not found") | |
} | |
tag = field.Tag | |
return tag, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment