telegram Gopher 台灣
@winampmaker
https://play.golang.org/p/RObzlfjZSRi
func struct2Map(model interface{}, tagName string) map[string]interface{} {
m := make(map[string]interface{})
r := reflect.ValueOf(model)
total := r.NumField()
for i := 0; i < total; i++ {
m[r.Type().Field(i).Tag.Get(tagName)] = r.Field(i).Interface()
}
return m
}
============================
"github.com/fatih/structs"
func StructtoMapbyTag(tr interface{}, tag string) map[string]interface{} {
t := make(map[string]interface{}) //儲存處理過的m
s := structs.New(tr)
m := s.Map() //先轉成map[string]interface{}
for key, value := range m {
t[s.Field(key).Tag(tag)] = value.(string)
}
return t
}