golang 使用反射处理 string, 用于 request body 中的 string 字段进行 trim
将 struct 中的string 字段进行 trim
func trimSpace(any interface{}) {
ov := reflect.ValueOf(any)
if ov.Kind() == reflect.Ptr && !ov.IsNil() {
ov = ov.Elem()
}
ot := reflect.TypeOf(any)
if ot.Kind() == reflect.Ptr {
ot = ot.Elem()
}
for i := 0; i < ot.NumField(); i++ {
field := ov.Field(i)
if field.Kind() == reflect.Ptr {
if field.Elem().Kind() == reflect.Struct {
trimSpace(field.Interface())
continue
}
field = field.Elem()
}
if field.CanInterface() && field.IsValid() {
if field.Kind() == reflect.String && field.CanSet() {
filedValue, ok := field.Interface().(string)
if ok {
filedValue = strings.TrimSpace(filedValue)
field.Set(reflect.ValueOf(filedValue))
}
}
}
}
}