-
Notifications
You must be signed in to change notification settings - Fork 36
/
conform.go
348 lines (311 loc) · 7.95 KB
/
conform.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package conform
import (
"bytes"
"errors"
"fmt"
"html/template"
"reflect"
"regexp"
"strings"
"unicode"
"unicode/utf8"
"github.com/etgryphon/stringUp"
)
type x map[string]string
type sanitizer func(string) string
var sanitizers = map[string]sanitizer{}
var patterns = map[string]*regexp.Regexp{
"numbers": regexp.MustCompile("[0-9]"),
"nonNumbers": regexp.MustCompile("[^0-9]"),
"alpha": regexp.MustCompile("[\\pL]"),
"nonAlpha": regexp.MustCompile("[^\\pL]"),
"name": regexp.MustCompile("[\\p{L}]([\\p{L}|[:space:]|\\-|\\']*[\\p{L}])*"),
}
// a valid email will only have one "@", but let's treat the last "@" as the domain part separator
func emailLocalPart(s string) string {
i := strings.LastIndex(s, "@")
if i == -1 {
return s
}
return s[0:i]
}
func emailDomainPart(s string) string {
i := strings.LastIndex(s, "@")
if i == -1 {
return ""
}
return s[i+1:]
}
func email(s string) string {
// According to rfc5321, "The local-part of a mailbox MUST BE treated as case sensitive"
return emailLocalPart(s) + "@" + strings.ToLower(emailDomainPart(s))
}
func camelTo(s, sep string) string {
var result string
var words []string
var lastPos int
rs := []rune(s)
for i := 0; i < len(rs); i++ {
if i > 0 && unicode.IsUpper(rs[i]) {
if initialism := startsWithInitialism(s[lastPos:]); initialism != "" {
words = append(words, initialism)
i += len(initialism) - 1
lastPos = i
continue
}
words = append(words, s[lastPos:i])
lastPos = i
}
}
// append the last word
if s[lastPos:] != "" {
words = append(words, s[lastPos:])
}
for k, word := range words {
if k > 0 {
result += sep
}
result += strings.ToLower(word)
}
return result
}
// startsWithInitialism returns the initialism if the given string begins with it
func startsWithInitialism(s string) string {
var initialism string
// the longest initialism is 5 char, the shortest 2
for i := 1; i <= 5; i++ {
if len(s) > i-1 && commonInitialisms[s[:i]] {
initialism = s[:i]
}
}
return initialism
}
// commonInitialisms, taken from
// https://github.com/golang/lint/blob/3d26dc39376c307203d3a221bada26816b3073cf/lint.go#L482
var commonInitialisms = map[string]bool{
"API": true,
"ASCII": true,
"CPU": true,
"CSS": true,
"DNS": true,
"EOF": true,
"GUID": true,
"HTML": true,
"HTTP": true,
"HTTPS": true,
"ID": true,
"IP": true,
"JSON": true,
"LHS": true,
"QPS": true,
"RAM": true,
"RHS": true,
"RPC": true,
"SLA": true,
"SMTP": true,
"SSH": true,
"TLS": true,
"TTL": true,
"UI": true,
"UID": true,
"UUID": true,
"URI": true,
"URL": true,
"UTF8": true,
"VM": true,
"XML": true,
}
func ucFirst(s string) string {
if s == "" {
return s
}
toRune, size := utf8.DecodeRuneInString(s)
if !unicode.IsLower(toRune) {
return s
}
buf := &bytes.Buffer{}
buf.WriteRune(unicode.ToUpper(toRune))
buf.WriteString(s[size:])
return buf.String()
}
func onlyNumbers(s string) string {
return patterns["nonNumbers"].ReplaceAllLiteralString(s, "")
}
func stripNumbers(s string) string {
return patterns["numbers"].ReplaceAllLiteralString(s, "")
}
func onlyAlpha(s string) string {
return patterns["nonAlpha"].ReplaceAllLiteralString(s, "")
}
func stripAlpha(s string) string {
return patterns["alpha"].ReplaceAllLiteralString(s, "")
}
func onlyOne(s string, m []x) string {
for _, v := range m {
for f, r := range v {
s = regexp.MustCompile(fmt.Sprintf("%s", f)).ReplaceAllLiteralString(s, r)
}
}
return s
}
func formatName(s string) string {
first := onlyOne(strings.ToLower(s), []x{
{"[^\\pL-\\s']": ""}, // cut off everything except [ alpha, hyphen, whitespace, apostrophe]
{"\\s{2,}": " "}, // trim more than two whitespaces to one
{"-{2,}": "-"}, // trim more than two hyphens to one
{"'{2,}": "'"}, // trim more than two apostrophes to one
{"( )*-( )*": "-"}, // trim enclosing whitespaces around hyphen
})
return strings.Title(patterns["name"].FindString(first))
}
func getSliceElemType(t reflect.Type) reflect.Type {
var elType reflect.Type
if t.Kind() == reflect.Ptr {
elType = t.Elem().Elem()
} else {
elType = t.Elem()
}
return elType
}
func transformValue(tags string, val reflect.Value) reflect.Value {
if val.Kind() == reflect.Ptr && val.IsNil() {
return val
}
var oldStr string
if val.Kind() == reflect.Ptr {
oldStr = val.Elem().String()
} else {
oldStr = val.String()
}
newStr := transformString(oldStr, tags)
var newVal reflect.Value
if val.Kind() == reflect.Ptr {
newVal = reflect.ValueOf(&newStr)
} else {
newVal = reflect.ValueOf(newStr)
}
return newVal.Convert(val.Type())
}
// Strings conforms strings based on reflection tags
func Strings(iface interface{}) error {
ifv := reflect.ValueOf(iface)
if ifv.Kind() != reflect.Ptr {
return errors.New("Not a pointer")
}
ift := reflect.Indirect(ifv).Type()
if ift.Kind() != reflect.Struct {
return nil
}
for i := 0; i < ift.NumField(); i++ {
v := ift.Field(i)
el := reflect.Indirect(ifv.Elem().FieldByName(v.Name))
switch el.Kind() {
case reflect.Slice:
if el.CanInterface() {
elType := getSliceElemType(v.Type)
// allow strings and string pointers
str := ""
if elType.ConvertibleTo(reflect.TypeOf(str)) || elType.ConvertibleTo(reflect.TypeOf(&str)) {
tags := v.Tag.Get("conform")
for i := 0; i < el.Len(); i++ {
el.Index(i).Set(transformValue(tags, el.Index(i)))
}
} else {
val := reflect.ValueOf(el.Interface())
for i := 0; i < val.Len(); i++ {
elVal := val.Index(i)
if elVal.Kind() != reflect.Ptr {
elVal = elVal.Addr()
}
Strings(elVal.Interface())
}
}
}
case reflect.Map:
if el.CanInterface() {
val := reflect.ValueOf(el.Interface())
for _, key := range val.MapKeys() {
mapValue := val.MapIndex(key)
mapValuePtr := reflect.New(mapValue.Type())
mapValuePtr.Elem().Set(mapValue)
if mapValuePtr.Elem().CanAddr() {
Strings(mapValuePtr.Elem().Addr().Interface())
}
val.SetMapIndex(key, reflect.Indirect(mapValuePtr))
}
}
case reflect.Struct:
if el.CanAddr() && el.Addr().CanInterface() {
// To handle "sql.NullString" we can assume that tags are added to a field of type struct rather than string
if tags := v.Tag.Get("conform"); tags != "" && el.CanSet() {
field := el.FieldByName("String")
str := field.String()
field.SetString(transformString(str, tags))
} else {
Strings(el.Addr().Interface())
}
}
case reflect.String:
if el.CanSet() {
tags := v.Tag.Get("conform")
input := el.String()
el.SetString(transformString(input, tags))
}
}
}
return nil
}
func transformString(input, tags string) string {
if tags == "" {
return input
}
for _, split := range strings.Split(tags, ",") {
switch split {
case "trim":
input = strings.TrimSpace(input)
case "ltrim":
input = strings.TrimLeft(input, " ")
case "rtrim":
input = strings.TrimRight(input, " ")
case "lower":
input = strings.ToLower(input)
case "upper":
input = strings.ToUpper(input)
case "title":
input = strings.Title(input)
case "camel":
input = stringUp.CamelCase(input)
case "snake":
input = camelTo(stringUp.CamelCase(input), "_")
case "slug":
input = camelTo(stringUp.CamelCase(input), "-")
case "ucfirst":
input = ucFirst(input)
case "name":
input = formatName(input)
case "email":
input = email(strings.TrimSpace(input))
case "num":
input = onlyNumbers(input)
case "!num":
input = stripNumbers(input)
case "alpha":
input = onlyAlpha(input)
case "!alpha":
input = stripAlpha(input)
case "!html":
input = template.HTMLEscapeString(input)
case "!js":
input = template.JSEscapeString(input)
default:
if s, ok := sanitizers[split]; ok {
input = s(input)
}
}
}
return input
}
// AddSanitizer associates a sanitizer with a key, which can be used in a Struct tag
func AddSanitizer(key string, s sanitizer) {
sanitizers[key] = s
}