Skip to content

Instantly share code, notes, and snippets.

@brunolkatz
Created October 30, 2020 19:39
Show Gist options
  • Save brunolkatz/b8a6f86f4b72e534a2c96cffb7daf9ee to your computer and use it in GitHub Desktop.
Save brunolkatz/b8a6f86f4b72e534a2c96cffb7daf9ee to your computer and use it in GitHub Desktop.
Get golang struct tags, returning name of field, value of tag and the index in struct
package main
import (
"errors"
"fmt"
"reflect"
)
type User struct {
Id int `json:"Id" queryStr:"Id"`
Name string `json:"FieldName" queryStr:"FieldName"`
Email string `json:"Email" queryStr:"Email"`
}
func main() {
user := &User{
Id: 1,
Name: "John Doe",
Email: "john@example",
}
tags, err := GetTagIndex(user, "queryStr")
if err != nil {
panic(err)
}
fmt.Println(tags)
return
}
type Tags struct {
FieldName string
ValueTag string
Index int64
}
func GetTagIndex(obj interface{}, tag string) (tags []Tags, err error){
tp := reflect.ValueOf(obj)
if reflect.ValueOf(obj).Kind() == reflect.Ptr {
tp = reflect.ValueOf(obj).Elem()
}
typeOfS := tp.Type()
for i := 0; i < tp.NumField(); i++ {
f, _ := typeOfS.FieldByName(typeOfS.Field(i).Name)
valueTag, ok := f.Tag.Lookup(tag)
if !ok {
continue
}
tags = append(tags, Tags{
ValueTag: valueTag,
FieldName: typeOfS.Field(i).Name,
Index: int64(i),
})
}
if len(tags) == 0 {
err = errors.New("tag not founded")
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment