// ToMapString 结构体转为Map[string]string
func ToMapString(in interface{}, tagName string) map[string]string {
out := make(map[string]string)
v := reflect.ValueOf(in)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct { // 非结构体返回错误提示
return nil
}
t := v.Type()
for i := 0; i < v.NumField(); i++ { // 遍历结构体字段
fi := t.Field(i)
tagValue := fi.Tag.Get(tagName) //获取标签里面的值 例如`form:"page"` 则获取到form里面的值 page
if tagValue != "" {
switch fi.Type.String() {
case "Int", "Int8", "Int16", "Int32", "Int64":
out[tagValue] = fmt.Sprintf("%d", v.Field(i).Int())
case "Float32", "Float64":
out[tagValue] = fmt.Sprintf("%f", v.Field(i).Float())
case "String":
out[tagValue] = v.Field(i).String()
case "Bool":
out[tagValue] = fmt.Sprintf("%v", v.Field(i).Bool())
default:
out[tagValue] = fmt.Sprintf("%v", v.Field(i).Interface())
}
}
}
return out
}
测试实例
type SearchRequest struct {
Page int64 `form:"page,default=1"`
Q string `form:"q,optional"` //可选参数
Size int64 `form:"size,default=10"`
}
{
name: "fuck",
args: args{
in: &SearchRequest{
Page: 60,
Q: "133",
Size: 1,
},
tagName: "form",
},
},