Repository navigation
Expand file tree
/
Copy pathvalidation.go
More file actions
533 lines (461 loc) · 14.9 KB
/
Copy pathvalidation.go
File metadata and controls
533 lines (461 loc) · 14.9 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
package nanite
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
)
var (
errRequired = "field is required"
errInvalidFormat = "invalid format"
errMustBeNumber = "must be a number"
errMustBeBoolean = "must be a boolean value"
emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
)
// ValidationError represents a single validation error with field and message.
type ValidationError struct {
Field string `json:"field"` // Field name that failed validation
Err string `json:"error"` // Error message describing the failure
}
// Error implements the error interface.
func (ve *ValidationError) Error() string {
return fmt.Sprintf("%s: %s", ve.Field, ve.Err)
}
// ValidatorFunc defines the signature for validation functions.
// It validates a string value and returns a pre-allocated ValidationError object.
type ValidatorFunc func(string) *ValidationError
// ValidationChain represents a chain of validation rules for a field.
type ValidationChain struct {
field string
rules []ValidatorFunc
preAllocatedErrors []*ValidationError
}
// ### Validation Support
// IsObject adds a rule that the field must be a JSON object.
//
//go:inline
func (vc *ValidationChain) IsObject() *ValidationChain {
// Pre-allocate the error
errObj := getValidationError(vc.field, "must be an object")
vc.preAllocatedErrors = append(vc.preAllocatedErrors, errObj)
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
if !strings.HasPrefix(value, "{") || !strings.HasSuffix(value, "}") {
return vc.preAllocatedErrors[errIndex]
}
return nil
})
return vc
}
// IsArray adds a rule that the field must be a JSON array.
func (vc *ValidationChain) IsArray() *ValidationChain {
// Pre-allocate the error
errObj := getValidationError(vc.field, "must be an array")
vc.preAllocatedErrors = append(vc.preAllocatedErrors, errObj)
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
if !strings.HasPrefix(value, "[") || !strings.HasSuffix(value, "]") {
return vc.preAllocatedErrors[errIndex]
}
return nil
})
return vc
}
// Custom adds a custom validation function to the chain.
func (vc *ValidationChain) Custom(fn func(string) error) *ValidationChain {
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
if err := fn(value); err != nil {
// This is the one case where we have to create an error at runtime
// since we can't know the error message in advance
return getValidationError(vc.field, err.Error())
}
return nil
})
return vc
}
// OneOf adds a rule that the field must be one of the specified options.
func (vc *ValidationChain) OneOf(options ...string) *ValidationChain {
// Pre-allocate the error - format the message at setup time
message := fmt.Sprintf("must be one of: %s", strings.Join(options, ", "))
errObj := getValidationError(vc.field, message)
vc.preAllocatedErrors = append(vc.preAllocatedErrors, errObj)
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
for _, option := range options {
if value == option {
return nil
}
}
return vc.preAllocatedErrors[errIndex]
})
return vc
}
// Matches adds a rule that the field must match the specified regular expression.
func (vc *ValidationChain) Matches(pattern string) *ValidationChain {
// Pre-compile the regex at setup time instead of per-request
re, err := regexp.Compile(pattern)
// Handle invalid pattern at setup time
if err != nil {
invalidPatternErr := getValidationError(vc.field, "invalid validation pattern")
vc.preAllocatedErrors = append(vc.preAllocatedErrors, invalidPatternErr)
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
return vc.preAllocatedErrors[errIndex]
})
return vc
}
// Pre-allocate for invalid format error
formatErr := getValidationError(vc.field, errInvalidFormat)
vc.preAllocatedErrors = append(vc.preAllocatedErrors, formatErr)
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
if !re.MatchString(value) {
return vc.preAllocatedErrors[errIndex]
}
return nil
})
return vc
}
// Length adds a rule that the field must have a length within specified range
func (vc *ValidationChain) Length(min, maxLength int) *ValidationChain {
// Pre-allocate error messages
tooShortErr := getValidationError(vc.field, fmt.Sprintf("must be at least %d characters", min))
tooLongErr := getValidationError(vc.field, fmt.Sprintf("must be at most %d characters", maxLength))
vc.preAllocatedErrors = append(vc.preAllocatedErrors, tooShortErr, tooLongErr)
// Store indices
tooShortIndex := len(vc.preAllocatedErrors) - 2
tooLongIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
length := len(value)
if length < min {
return vc.preAllocatedErrors[tooShortIndex]
}
if length > maxLength {
return vc.preAllocatedErrors[tooLongIndex]
}
return nil
})
return vc
}
// Max adds a rule that the field must be at most a specified integer value.
func (vc *ValidationChain) Max(max int) *ValidationChain {
// Pre-allocate errors
numErr := getValidationError(vc.field, errMustBeNumber)
maxErr := getValidationError(vc.field, fmt.Sprintf("must be at most %d", max))
vc.preAllocatedErrors = append(vc.preAllocatedErrors, numErr, maxErr)
numErrIndex := len(vc.preAllocatedErrors) - 2
maxErrIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
num, err := strconv.Atoi(value)
if err != nil {
return vc.preAllocatedErrors[numErrIndex]
}
if num > max {
return vc.preAllocatedErrors[maxErrIndex]
}
return nil
})
return vc
}
// Min adds a rule that the field must be at least a specified integer value.
func (vc *ValidationChain) Min(min int) *ValidationChain {
// Pre-allocate errors
numErr := getValidationError(vc.field, errMustBeNumber)
minErr := getValidationError(vc.field, fmt.Sprintf("must be at least %d", min))
vc.preAllocatedErrors = append(vc.preAllocatedErrors, numErr, minErr)
numErrIndex := len(vc.preAllocatedErrors) - 2
minErrIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
num, err := strconv.Atoi(value)
if err != nil {
return vc.preAllocatedErrors[numErrIndex]
}
if num < min {
return vc.preAllocatedErrors[minErrIndex]
}
return nil
})
return vc
}
// IsBoolean adds a rule that the field must be a boolean value.
func (vc *ValidationChain) IsBoolean() *ValidationChain {
// Pre-allocate the error
errObj := getValidationError(vc.field, errMustBeBoolean)
vc.preAllocatedErrors = append(vc.preAllocatedErrors, errObj)
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
lowerVal := strings.ToLower(value)
if lowerVal != "true" && lowerVal != "false" && lowerVal != "1" && lowerVal != "0" {
return vc.preAllocatedErrors[errIndex]
}
return nil
})
return vc
}
// IsFloat adds a rule that the field must be a floating-point number.
//
//go:inline
func (vc *ValidationChain) IsFloat() *ValidationChain {
// Pre-allocate the error
errObj := getValidationError(vc.field, errMustBeNumber)
vc.preAllocatedErrors = append(vc.preAllocatedErrors, errObj)
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
if _, err := strconv.ParseFloat(value, 64); err != nil {
return vc.preAllocatedErrors[errIndex]
}
return nil
})
return vc
}
// IsInt adds a rule that the field must be an integer.
//
//go:inline
func (vc *ValidationChain) IsInt() *ValidationChain {
// Pre-allocate the error
errObj := getValidationError(vc.field, "must be an integer")
vc.preAllocatedErrors = append(vc.preAllocatedErrors, errObj)
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
if _, err := strconv.Atoi(value); err != nil {
return vc.preAllocatedErrors[errIndex]
}
return nil
})
return vc
}
// IsEmail adds a rule that the field must be a valid email address.
//
//go:inline
func (vc *ValidationChain) IsEmail() *ValidationChain {
// Pre-allocate the error
errObj := getValidationError(vc.field, "invalid email format")
vc.preAllocatedErrors = append(vc.preAllocatedErrors, errObj)
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if value == "" {
return nil
}
if !emailRegex.MatchString(value) {
return vc.preAllocatedErrors[errIndex]
}
return nil
})
return vc
}
// Required adds a rule that the field must not be empty.
//
//go:inline
func (vc *ValidationChain) Required() *ValidationChain {
errObj := getValidationError(vc.field, errRequired)
vc.preAllocatedErrors = append(vc.preAllocatedErrors, errObj)
// Store index for this specific error
errIndex := len(vc.preAllocatedErrors) - 1
vc.rules = append(vc.rules, func(value string) *ValidationError {
if strings.TrimSpace(value) == "" {
// Return the pre-allocated error directly
return vc.preAllocatedErrors[errIndex]
}
return nil
})
return vc
}
// NewValidationChain creates a new ValidationChain for the specified field.
func NewValidationChain(field string) *ValidationChain {
return getValidationChain(field)
}
// Release returns the ValidationChain to the pool
func (vc *ValidationChain) Release() {
// Return all pre-allocated errors to the pool
for _, err := range vc.preAllocatedErrors {
putValidationError(err)
}
vc.preAllocatedErrors = vc.preAllocatedErrors[:0]
vc.rules = vc.rules[:0]
putValidationChain(vc)
}
// JSONParsingConfig provides configuration options for the JSONParsingMiddleware
type JSONParsingConfig struct {
MaxSize int64 // Maximum allowed size for JSON request bodies
ErrorHandler func(*Context, error) // Custom error handler for parsing errors
TargetKey string // Context key where parsed JSON is stored (default: "body")
RequireJSON bool // Require all requests to have application/json content type
AllowEmptyBody bool // Allow empty request bodies (results in empty object)
}
// DefaultJSONConfig returns a default configuration for JSON parsing middleware
func DefaultJSONConfig() JSONParsingConfig {
return JSONParsingConfig{
MaxSize: 10 << 20, // 10MB
TargetKey: "body",
RequireJSON: false,
AllowEmptyBody: true,
}
}
// JSONParsingMiddleware creates middleware that parses JSON request bodies.
// It uses an optimized io.TeeReader approach to parse the body without
// consuming it, making it available for downstream handlers.
//
// Parameters:
// - config: Optional configuration for the middleware. If nil, defaults are used.
//
// Returns:
// - MiddlewareFunc: Middleware function that can be registered with the router
func JSONParsingMiddleware(config *JSONParsingConfig) MiddlewareFunc {
// Use default config if none provided
cfg := DefaultJSONConfig()
if config != nil {
cfg = *config
}
return func(ctx *Context, next func()) {
if ctx.IsAborted() {
return
}
// Check if we need to process this request
contentType := ctx.Request.Header.Get("Content-Type")
isJSON := strings.HasPrefix(contentType, "application/json")
if !isJSON {
if cfg.RequireJSON {
// If JSON is required but content-type is not JSON, abort
if cfg.ErrorHandler != nil {
cfg.ErrorHandler(ctx, fmt.Errorf("content type must be application/json"))
} else {
ctx.JSON(http.StatusUnsupportedMediaType, map[string]interface{}{
"error": "content type must be application/json",
})
}
return
}
// If JSON is not required and content-type is not JSON, skip parsing
next()
return
}
// Check Content-Length if available for early rejection
if ctx.Request.ContentLength > cfg.MaxSize && ctx.Request.ContentLength != -1 {
if cfg.ErrorHandler != nil {
cfg.ErrorHandler(ctx, fmt.Errorf("request body too large"))
} else {
ctx.JSON(http.StatusRequestEntityTooLarge, map[string]interface{}{
"error": "request body too large",
})
}
return
}
// Get buffer from pool
buffer := bufferPool.Get().(*bytes.Buffer)
buffer.Reset()
defer bufferPool.Put(buffer)
// Handle empty bodies
if ctx.Request.ContentLength == 0 {
if cfg.AllowEmptyBody {
// Use pooled map for empty object
ctx.setPooledMap(cfg.TargetKey, getMap())
next()
return
} else {
if cfg.ErrorHandler != nil {
cfg.ErrorHandler(ctx, fmt.Errorf("empty request body not allowed"))
} else {
ctx.JSON(http.StatusBadRequest, map[string]interface{}{
"error": "empty request body not allowed",
})
}
return
}
}
// Read the body into a pooled buffer with a hard upper bound.
readBytes, readErr := io.CopyN(buffer, ctx.Request.Body, cfg.MaxSize+1)
if readErr != nil && readErr != io.EOF {
if cfg.ErrorHandler != nil {
cfg.ErrorHandler(ctx, readErr)
} else {
ctx.JSON(http.StatusBadRequest, map[string]interface{}{
"error": "invalid request body",
})
}
return
}
if readBytes > cfg.MaxSize {
if cfg.ErrorHandler != nil {
cfg.ErrorHandler(ctx, fmt.Errorf("request body too large"))
} else {
ctx.JSON(http.StatusRequestEntityTooLarge, map[string]interface{}{
"error": "request body too large",
})
}
return
}
if readBytes == 0 {
if cfg.AllowEmptyBody {
ctx.setPooledMap(cfg.TargetKey, getMap())
next()
return
}
if cfg.ErrorHandler != nil {
cfg.ErrorHandler(ctx, fmt.Errorf("empty request body not allowed"))
} else {
ctx.JSON(http.StatusBadRequest, map[string]interface{}{
"error": "empty request body not allowed",
})
}
return
}
// Parse the JSON from the buffered bytes.
body := getMap()
if err := json.Unmarshal(buffer.Bytes(), &body); err != nil {
putMap(body)
if cfg.ErrorHandler != nil {
cfg.ErrorHandler(ctx, err)
} else {
ctx.JSON(http.StatusBadRequest, map[string]interface{}{
"error": "invalid JSON: " + err.Error(),
})
}
return
}
// Close original body and replace with buffered copy for downstream handlers
ctx.Request.Body.Close()
ctx.reusedBody.Reset(buffer.Bytes())
ctx.Request.Body = &ctx.reusedBody
// Store parsed body in context with the configured key
ctx.setPooledMap(cfg.TargetKey, body)
// Proceed to the next middleware or handler
next()
}
}