Skip to content

Instantly share code, notes, and snippets.

@josephspurrier
Last active August 19, 2017 11:14
Show Gist options
  • Save josephspurrier/c8f81a6ba64603aa913097e83b32dce3 to your computer and use it in GitHub Desktop.
Save josephspurrier/c8f81a6ba64603aa913097e83b32dce3 to your computer and use it in GitHub Desktop.
Get Struct Tag in Go
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