SpecialCharsMapOrStruct automatically encodes string values/attributes for map/struct. Note that, if operation on struct, the given parameter `mapOrStruct` should be type of pointer to struct. For example: var m = map{} var s = struct{}{} OK: SpecialCharsMapOrStruct(m) OK: SpecialCharsMapOrStruct(
(mapOrStruct any)
| 73 | // OK: SpecialCharsMapOrStruct(&s) |
| 74 | // Error: SpecialCharsMapOrStruct(s) |
| 75 | func SpecialCharsMapOrStruct(mapOrStruct any) error { |
| 76 | var ( |
| 77 | reflectValue = reflect.ValueOf(mapOrStruct) |
| 78 | reflectKind = reflectValue.Kind() |
| 79 | originalKind = reflectKind |
| 80 | ) |
| 81 | for reflectValue.IsValid() && (reflectKind == reflect.Pointer || reflectKind == reflect.Interface) { |
| 82 | reflectValue = reflectValue.Elem() |
| 83 | reflectKind = reflectValue.Kind() |
| 84 | } |
| 85 | |
| 86 | switch reflectKind { |
| 87 | case reflect.Map: |
| 88 | var ( |
| 89 | mapKeys = reflectValue.MapKeys() |
| 90 | mapValue reflect.Value |
| 91 | ) |
| 92 | for _, key := range mapKeys { |
| 93 | mapValue = reflectValue.MapIndex(key) |
| 94 | switch mapValue.Kind() { |
| 95 | case reflect.String: |
| 96 | reflectValue.SetMapIndex(key, reflect.ValueOf(SpecialChars(mapValue.String()))) |
| 97 | case reflect.Interface: |
| 98 | if mapValue.Elem().Kind() == reflect.String { |
| 99 | reflectValue.SetMapIndex( |
| 100 | key, |
| 101 | reflect.ValueOf(SpecialChars(mapValue.Elem().String())), |
| 102 | ) |
| 103 | } |
| 104 | default: |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | case reflect.Struct: |
| 109 | if originalKind != reflect.Pointer { |
| 110 | return gerror.NewCodef( |
| 111 | gcode.CodeInvalidParameter, |
| 112 | `invalid input parameter type "%s", should be type of pointer to struct`, |
| 113 | reflect.TypeOf(mapOrStruct).String(), |
| 114 | ) |
| 115 | } |
| 116 | var fieldValue reflect.Value |
| 117 | for i := 0; i < reflectValue.NumField(); i++ { |
| 118 | fieldValue = reflectValue.Field(i) |
| 119 | switch fieldValue.Kind() { |
| 120 | case reflect.String: |
| 121 | fieldValue.Set( |
| 122 | reflect.ValueOf( |
| 123 | SpecialChars(fieldValue.String()), |
| 124 | ), |
| 125 | ) |
| 126 | default: |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | default: |
| 131 | return gerror.NewCodef( |
| 132 | gcode.CodeInvalidParameter, |
searching dependent graphs…