forked from jkaninda/okapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
798 lines (660 loc) · 28.7 KB
/
errors.go
File metadata and controls
798 lines (660 loc) · 28.7 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
/*
* MIT License
*
* Copyright (c) 2025 Jonas Kaninda
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package okapi
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
// ErrorResponse represents a standardized error response structure
type ErrorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Details string `json:"details,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
// ValidationError represents validation error details
type ValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Value any `json:"value,omitempty"`
}
// ValidationErrorResponse extends ErrorResponse for validation errors
type ValidationErrorResponse struct {
ErrorResponse
Errors []ValidationError `json:"errors"`
}
// ProblemDetail represents RFC 7807 Problem Details for HTTP APIs
// See: https://tools.ietf.org/html/rfc7807
type ProblemDetail struct {
Type string `json:"type" xml:"type"`
Title string `json:"title" xml:"title"`
Status int `json:"status" xml:"status"`
Detail string `json:"detail,omitempty" xml:"detail,omitempty"`
Instance string `json:"instance,omitempty" xml:"instance,omitempty"`
Extensions map[string]any `json:"-" xml:"-"`
}
// MarshalJSON implements custom JSON marshaling to include extensions
func (p ProblemDetail) MarshalJSON() ([]byte, error) {
type Alias ProblemDetail
base := struct {
Alias
}{
Alias: (Alias)(p),
}
baseMap := make(map[string]any)
data, err := json.Marshal(base)
if err != nil {
return nil, err
}
if err = json.Unmarshal(data, &baseMap); err != nil {
return nil, err
}
for k, v := range p.Extensions {
baseMap[k] = v
}
return json.Marshal(baseMap)
}
// ErrorHandler is a function type that formats error responses
type ErrorHandler func(c *Context, code int, message string, err error) error
// ErrorFormat defines the format for error responses
type ErrorFormat string
const (
// ErrorFormatDefault uses the standard ErrorResponse format
ErrorFormatDefault ErrorFormat = "default"
// ErrorFormatProblemJSON uses RFC 7807 Problem Details (application/problem+json)
ErrorFormatProblemJSON ErrorFormat = "problem+json"
// ErrorFormatProblemXML uses RFC 7807 Problem Details (application/problem+xml)
ErrorFormatProblemXML ErrorFormat = "problem+xml"
)
// ErrorHandlerConfig configures the error handler behavior
type ErrorHandlerConfig struct {
// Format specifies the error response format
Format ErrorFormat
// TypePrefix is the base URI for problem types (e.g., "https://api.example.com/errors/")
TypePrefix string
IncludeInstance bool
IncludeTimestamp bool
// CustomFields allows adding custom fields to all error responses
CustomFields map[string]any
}
// DefaultErrorHandler provides the standard error response format
func DefaultErrorHandler(c *Context, code int, message string, err error) error {
details := ""
if err != nil {
details = err.Error()
}
return c.JSON(code, ErrorResponse{
Code: code,
Message: message,
Details: details,
Timestamp: time.Now(),
})
}
// ProblemDetailErrorHandler creates an error handler that returns RFC 7807 Problem Details
func ProblemDetailErrorHandler(config *ErrorHandlerConfig) ErrorHandler {
if config == nil {
config = &ErrorHandlerConfig{
Format: ErrorFormatProblemJSON,
TypePrefix: "about:blank",
IncludeInstance: true,
IncludeTimestamp: true,
}
}
return func(c *Context, code int, message string, err error) error {
problem := ProblemDetail{
Type: config.TypePrefix,
Title: http.StatusText(code),
Status: code,
Extensions: make(map[string]any),
}
// Add detail if provided
if message != "" && message != http.StatusText(code) {
problem.Detail = message
} else if err != nil {
problem.Detail = err.Error()
}
// Add instance (request path)
if config.IncludeInstance {
problem.Instance = c.Path()
}
// Add timestamp
if config.IncludeTimestamp {
problem.Extensions["timestamp"] = time.Now().Format(time.RFC3339)
}
// Add custom fields
for k, v := range config.CustomFields {
problem.Extensions[k] = v
}
if config.Format == ErrorFormatProblemXML {
return c.xmlProblemError(code, problem)
}
return c.jsonProblemError(code, problem)
}
}
// NewProblemDetail creates a new ProblemDetail with common defaults
func NewProblemDetail(code int, typeURI, detail string) *ProblemDetail {
return &ProblemDetail{
Type: typeURI,
Title: http.StatusText(code),
Status: code,
Detail: detail,
Extensions: make(map[string]any),
}
}
// WithInstance adds an instance URI to the problem detail
func (p *ProblemDetail) WithInstance(instance string) *ProblemDetail {
p.Instance = instance
return p
}
// WithExtension adds a custom extension field
func (p *ProblemDetail) WithExtension(key string, value any) *ProblemDetail {
if p.Extensions == nil {
p.Extensions = make(map[string]any)
}
p.Extensions[key] = value
return p
}
// WithTimestamp adds a timestamp extension
func (p *ProblemDetail) WithTimestamp() *ProblemDetail {
return p.WithExtension("timestamp", time.Now().Format(time.RFC3339))
}
// ********** Error Handler Configuration Options **********
// WithErrorHandler sets a custom error handler for the application
func WithErrorHandler(handler ErrorHandler) OptionFunc {
return func(o *Okapi) {
o.errorHandler = handler
}
}
// WithDefaultErrorHandler sets the default error handler (useful for resetting)
func WithDefaultErrorHandler() OptionFunc {
return func(o *Okapi) {
o.errorHandler = DefaultErrorHandler
}
}
// WithProblemDetailErrorHandler sets RFC 7807 Problem Details error handler
func WithProblemDetailErrorHandler(config *ErrorHandlerConfig) OptionFunc {
return func(o *Okapi) {
o.errorHandler = ProblemDetailErrorHandler(config)
}
}
// WithSimpleProblemDetailErrorHandler sets RFC 7807 Problem Details with default config
func WithSimpleProblemDetailErrorHandler() OptionFunc {
return WithProblemDetailErrorHandler(nil)
}
// SetErrorHandler allows setting a custom error handler at the context level
// This overrides the global error handler for this specific request
func (c *Context) SetErrorHandler(handler ErrorHandler) {
c.errorHandler = handler
}
// getContextErrorHandler returns context-level handler, then global, then default
func (c *Context) getContextErrorHandler() ErrorHandler {
if c.errorHandler != nil {
return c.errorHandler
}
if c.okapi != nil {
if c.okapi.errorHandler != nil {
return c.okapi.errorHandler
}
}
return DefaultErrorHandler
}
// ************* Context Errors ****************
// ********** Core Error Methods *************
// Error writes a basic error response with the given status code and message.
func (c *Context) Error(code int, message string) error {
c.response.WriteHeader(code)
_, err := c.response.Write([]byte(message))
if err != nil {
return fmt.Errorf("failed to write error response: %w", err)
}
return nil
}
// AbortWithError writes a standardized error response using the configured error handler.
func (c *Context) AbortWithError(code int, err error) error {
message := http.StatusText(code)
return c.getContextErrorHandler()(c, code, message, err)
}
// abortWithError writes a standardized error response with custom message using the configured error handler.
func (c *Context) abortWithError(code int, msg string, err error) error {
return c.getContextErrorHandler()(c, code, msg, err)
}
// AbortWithJSON writes a custom JSON error response.
func (c *Context) AbortWithJSON(code int, jsonObj interface{}) error {
return c.JSON(code, jsonObj)
}
// AbortWithProblemDetail writes an RFC 7807 Problem Details response.
func (c *Context) AbortWithProblemDetail(problem *ProblemDetail) error {
return c.jsonProblemError(problem.Status, problem)
}
// AbortWithStatus writes an error response with status code and custom message.
// Note: This method maintains backward compatibility by using the default ErrorResponse structure.
// For full customization, use AbortWithError or set a custom ErrorHandler.
func (c *Context) AbortWithStatus(code int, message string) error {
return c.JSON(code, ErrorResponse{
Code: code,
Message: http.StatusText(code),
Details: message,
Timestamp: time.Now(),
})
}
// ********** Helper Method *************
// abortWithStatus is a helper for consistent status-based error responses
func (c *Context) abortWithStatus(code int, defaultMsg string, msg string, err ...error) error {
var internalErr error
message := defaultMsg
if len(msg) > 0 && msg != "" {
message = msg
}
if len(err) > 0 && err[0] != nil {
internalErr = err[0]
} else {
internalErr = errors.New(message)
}
return c.abortWithError(code, message, internalErr)
}
// ********** 4xx Client Error Methods *************
// ErrorBadRequest writes a 400 Bad request response.
func (c *Context) ErrorBadRequest(message any) error {
return c.JSON(http.StatusBadRequest, message)
}
// AbortBadRequest writes a standardized 400 Bad request response.
func (c *Context) AbortBadRequest(msg string, err ...error) error {
return c.abortWithStatus(http.StatusBadRequest, "Bad request", msg, err...)
}
// ErrorUnauthorized writes a 401 Unauthorized response.
func (c *Context) ErrorUnauthorized(message any) error {
return c.JSON(http.StatusUnauthorized, message)
}
// AbortUnauthorized writes a standardized 401 Unauthorized response.
func (c *Context) AbortUnauthorized(msg string, err ...error) error {
return c.abortWithStatus(http.StatusUnauthorized, "Unauthorized", msg, err...)
}
// ErrorPaymentRequired writes a 402 Payment Required response.
func (c *Context) ErrorPaymentRequired(message any) error {
return c.JSON(http.StatusPaymentRequired, message)
}
// AbortPaymentRequired writes a standardized 402 Payment Required response.
func (c *Context) AbortPaymentRequired(msg string, err ...error) error {
return c.abortWithStatus(http.StatusPaymentRequired, "Payment Required", msg, err...)
}
// ErrorForbidden writes a 403 Forbidden response.
func (c *Context) ErrorForbidden(message any) error {
return c.JSON(http.StatusForbidden, message)
}
// AbortForbidden writes a standardized 403 Forbidden response.
func (c *Context) AbortForbidden(msg string, err ...error) error {
return c.abortWithStatus(http.StatusForbidden, "Forbidden", msg, err...)
}
// ErrorNotFound writes a 404 Not Found response.
func (c *Context) ErrorNotFound(message any) error {
return c.JSON(http.StatusNotFound, message)
}
// AbortNotFound writes a standardized 404 Not Found response.
func (c *Context) AbortNotFound(msg string, err ...error) error {
return c.abortWithStatus(http.StatusNotFound, "Not Found", msg, err...)
}
// ErrorMethodNotAllowed writes a 405 Method Not Allowed response.
func (c *Context) ErrorMethodNotAllowed(message any) error {
return c.JSON(http.StatusMethodNotAllowed, message)
}
// AbortMethodNotAllowed writes a standardized 405 Method Not Allowed response.
func (c *Context) AbortMethodNotAllowed(msg string, err ...error) error {
return c.abortWithStatus(http.StatusMethodNotAllowed, "Method Not Allowed", msg, err...)
}
// ErrorNotAcceptable writes a 406 Not Acceptable response.
func (c *Context) ErrorNotAcceptable(message any) error {
return c.JSON(http.StatusNotAcceptable, message)
}
// AbortNotAcceptable writes a standardized 406 Not Acceptable response.
func (c *Context) AbortNotAcceptable(msg string, err ...error) error {
return c.abortWithStatus(http.StatusNotAcceptable, "Not Acceptable", msg, err...)
}
// ErrorProxyAuthRequired writes a 407 Proxy Authentication Required response.
func (c *Context) ErrorProxyAuthRequired(message any) error {
return c.JSON(http.StatusProxyAuthRequired, message)
}
// AbortProxyAuthRequired writes a standardized 407 Proxy Authentication Required response.
func (c *Context) AbortProxyAuthRequired(msg string, err ...error) error {
return c.abortWithStatus(http.StatusProxyAuthRequired, "Proxy Authentication Required", msg, err...)
}
// ErrorRequestTimeout writes a 408 request Timeout response.
func (c *Context) ErrorRequestTimeout(message any) error {
return c.JSON(http.StatusRequestTimeout, message)
}
// AbortRequestTimeout writes a standardized 408 request Timeout response.
func (c *Context) AbortRequestTimeout(msg string, err ...error) error {
return c.abortWithStatus(http.StatusRequestTimeout, "request Timeout", msg, err...)
}
// ErrorConflict writes a 409 Conflict response.
func (c *Context) ErrorConflict(message any) error {
return c.JSON(http.StatusConflict, message)
}
// AbortConflict writes a standardized 409 Conflict response.
func (c *Context) AbortConflict(msg string, err ...error) error {
return c.abortWithStatus(http.StatusConflict, "Conflict", msg, err...)
}
// ErrorGone writes a 410 Gone response.
func (c *Context) ErrorGone(message any) error {
return c.JSON(http.StatusGone, message)
}
// AbortGone writes a standardized 410 Gone response.
func (c *Context) AbortGone(msg string, err ...error) error {
return c.abortWithStatus(http.StatusGone, "Gone", msg, err...)
}
// ErrorLengthRequired writes a 411 Length Required response.
func (c *Context) ErrorLengthRequired(message any) error {
return c.JSON(http.StatusLengthRequired, message)
}
// AbortLengthRequired writes a standardized 411 Length Required response.
func (c *Context) AbortLengthRequired(msg string, err ...error) error {
return c.abortWithStatus(http.StatusLengthRequired, "Length Required", msg, err...)
}
// ErrorPreconditionFailed writes a 412 Precondition Failed response.
func (c *Context) ErrorPreconditionFailed(message any) error {
return c.JSON(http.StatusPreconditionFailed, message)
}
// AbortPreconditionFailed writes a standardized 412 Precondition Failed response.
func (c *Context) AbortPreconditionFailed(msg string, err ...error) error {
return c.abortWithStatus(http.StatusPreconditionFailed, "Precondition Failed", msg, err...)
}
// ErrorRequestEntityTooLarge writes a 413 request Entity Too Large response.
func (c *Context) ErrorRequestEntityTooLarge(message any) error {
return c.JSON(http.StatusRequestEntityTooLarge, message)
}
// AbortRequestEntityTooLarge writes a standardized 413 request Entity Too Large response.
func (c *Context) AbortRequestEntityTooLarge(msg string, err ...error) error {
return c.abortWithStatus(http.StatusRequestEntityTooLarge, "request Entity Too Large", msg, err...)
}
// ErrorRequestURITooLong writes a 414 request-URI Too Long response.
func (c *Context) ErrorRequestURITooLong(message any) error {
return c.JSON(http.StatusRequestURITooLong, message)
}
// AbortRequestURITooLong writes a standardized 414 request-URI Too Long response.
func (c *Context) AbortRequestURITooLong(msg string, err ...error) error {
return c.abortWithStatus(http.StatusRequestURITooLong, "request-URI Too Long", msg, err...)
}
// ErrorUnsupportedMediaType writes a 415 Unsupported Media Type response.
func (c *Context) ErrorUnsupportedMediaType(message any) error {
return c.JSON(http.StatusUnsupportedMediaType, message)
}
// AbortUnsupportedMediaType writes a standardized 415 Unsupported Media Type response.
func (c *Context) AbortUnsupportedMediaType(msg string, err ...error) error {
return c.abortWithStatus(http.StatusUnsupportedMediaType, "Unsupported Media Type", msg, err...)
}
// ErrorRequestedRangeNotSatisfiable writes a 416 Requested Range Not Satisfiable response.
func (c *Context) ErrorRequestedRangeNotSatisfiable(message any) error {
return c.JSON(http.StatusRequestedRangeNotSatisfiable, message)
}
// AbortRequestedRangeNotSatisfiable writes a standardized 416 Requested Range Not Satisfiable response.
func (c *Context) AbortRequestedRangeNotSatisfiable(msg string, err ...error) error {
return c.abortWithStatus(http.StatusRequestedRangeNotSatisfiable, "Requested Range Not Satisfiable", msg, err...)
}
// ErrorExpectationFailed writes a 417 Expectation Failed response.
func (c *Context) ErrorExpectationFailed(message any) error {
return c.JSON(http.StatusExpectationFailed, message)
}
// AbortExpectationFailed writes a standardized 417 Expectation Failed response.
func (c *Context) AbortExpectationFailed(msg string, err ...error) error {
return c.abortWithStatus(http.StatusExpectationFailed, "Expectation Failed", msg, err...)
}
// ErrorTeapot writes a 418 I'm a teapot response (RFC 2324).
func (c *Context) ErrorTeapot(message any) error {
return c.JSON(http.StatusTeapot, message)
}
// AbortTeapot writes a standardized 418 I'm a teapot response.
func (c *Context) AbortTeapot(msg string, err ...error) error {
return c.abortWithStatus(http.StatusTeapot, "I'm a teapot", msg, err...)
}
// ErrorMisdirectedRequest writes a 421 Misdirected request response.
func (c *Context) ErrorMisdirectedRequest(message any) error {
return c.JSON(http.StatusMisdirectedRequest, message)
}
// AbortMisdirectedRequest writes a standardized 421 Misdirected request response.
func (c *Context) AbortMisdirectedRequest(msg string, err ...error) error {
return c.abortWithStatus(http.StatusMisdirectedRequest, "Misdirected request", msg, err...)
}
// ErrorUnprocessableEntity writes a 422 Unprocessable Entity response.
func (c *Context) ErrorUnprocessableEntity(message any) error {
return c.JSON(http.StatusUnprocessableEntity, message)
}
// AbortValidationError writes a standardized 422 Unprocessable Entity response.
func (c *Context) AbortValidationError(msg string, err ...error) error {
return c.abortWithStatus(http.StatusUnprocessableEntity, "Unprocessable Entity", msg, err...)
}
// AbortValidationErrors writes a detailed validation error response.
// Note: This method always uses the default ValidationErrorResponse structure
// regardless of custom error handlers, as it has a specific format for validation errors.
func (c *Context) AbortValidationErrors(errors []ValidationError, msg ...string) error {
message := "Validation failed"
if len(msg) > 0 && msg[0] != "" {
message = msg[0]
}
return c.JSON(http.StatusUnprocessableEntity, ValidationErrorResponse{
ErrorResponse: ErrorResponse{
Code: http.StatusUnprocessableEntity,
Message: message,
Timestamp: time.Now(),
},
Errors: errors,
})
}
// AbortValidationErrorsWithProblemDetail writes validation errors as RFC 7807 Problem Details
func (c *Context) AbortValidationErrorsWithProblemDetail(errors []ValidationError, msg ...string) error {
message := "Validation failed"
if len(msg) > 0 && msg[0] != "" {
message = msg[0]
}
problem := NewProblemDetail(
http.StatusUnprocessableEntity,
"https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1",
message,
).WithInstance(c.Path()).
WithTimestamp().
WithExtension("errors", errors)
return c.AbortWithProblemDetail(problem)
}
// ErrorNotModified writes a 304 Not Modified response.
func (c *Context) ErrorNotModified() error {
c.response.WriteHeader(http.StatusNotModified)
return nil
}
// AbortNotModified writes a 304 Not Modified response.
// Per HTTP spec, 304 responses must not contain a body.
func (c *Context) AbortNotModified() error {
c.response.WriteHeader(http.StatusNotModified)
return nil
}
// ErrorLocked writes a 423 Locked response.
func (c *Context) ErrorLocked(message any) error {
return c.JSON(http.StatusLocked, message)
}
// AbortLocked writes a standardized 423 Locked response.
func (c *Context) AbortLocked(msg string, err ...error) error {
return c.abortWithStatus(http.StatusLocked, "Locked", msg, err...)
}
// ErrorFailedDependency writes a 424 Failed Dependency response.
func (c *Context) ErrorFailedDependency(message any) error {
return c.JSON(http.StatusFailedDependency, message)
}
// AbortFailedDependency writes a standardized 424 Failed Dependency response.
func (c *Context) AbortFailedDependency(msg string, err ...error) error {
return c.abortWithStatus(http.StatusFailedDependency, "Failed Dependency", msg, err...)
}
// ErrorTooEarly writes a 425 Too Early response.
func (c *Context) ErrorTooEarly(message any) error {
return c.JSON(http.StatusTooEarly, message)
}
// AbortTooEarly writes a standardized 425 Too Early response.
func (c *Context) AbortTooEarly(msg string, err ...error) error {
return c.abortWithStatus(http.StatusTooEarly, "Too Early", msg, err...)
}
// ErrorUpgradeRequired writes a 426 Upgrade Required response.
func (c *Context) ErrorUpgradeRequired(message any) error {
return c.JSON(http.StatusUpgradeRequired, message)
}
// AbortUpgradeRequired writes a standardized 426 Upgrade Required response.
func (c *Context) AbortUpgradeRequired(msg string, err ...error) error {
return c.abortWithStatus(http.StatusUpgradeRequired, "Upgrade Required", msg, err...)
}
// ErrorPreconditionRequired writes a 428 Precondition Required response.
func (c *Context) ErrorPreconditionRequired(message any) error {
return c.JSON(http.StatusPreconditionRequired, message)
}
// AbortPreconditionRequired writes a standardized 428 Precondition Required response.
func (c *Context) AbortPreconditionRequired(msg string, err ...error) error {
return c.abortWithStatus(http.StatusPreconditionRequired, "Precondition Required", msg, err...)
}
// ErrorTooManyRequests writes a 429 Too Many Requests response.
func (c *Context) ErrorTooManyRequests(message any) error {
return c.JSON(http.StatusTooManyRequests, message)
}
// AbortTooManyRequests writes a standardized 429 Too Many Requests response.
func (c *Context) AbortTooManyRequests(msg string, err ...error) error {
return c.abortWithStatus(http.StatusTooManyRequests, "Too Many Requests", msg, err...)
}
// ErrorRequestHeaderFieldsTooLarge writes a 431 request Header Fields Too Large response.
func (c *Context) ErrorRequestHeaderFieldsTooLarge(message any) error {
return c.JSON(http.StatusRequestHeaderFieldsTooLarge, message)
}
// AbortRequestHeaderFieldsTooLarge writes a standardized 431 request Header Fields Too Large response.
func (c *Context) AbortRequestHeaderFieldsTooLarge(msg string, err ...error) error {
return c.abortWithStatus(http.StatusRequestHeaderFieldsTooLarge, "request Header Fields Too Large", msg, err...)
}
// ErrorUnavailableForLegalReasons writes a 451 Unavailable For Legal Reasons response.
func (c *Context) ErrorUnavailableForLegalReasons(message any) error {
return c.JSON(http.StatusUnavailableForLegalReasons, message)
}
// AbortUnavailableForLegalReasons writes a standardized 451 Unavailable For Legal Reasons response.
func (c *Context) AbortUnavailableForLegalReasons(msg string, err ...error) error {
return c.abortWithStatus(http.StatusUnavailableForLegalReasons, "Unavailable For Legal Reasons", msg, err...)
}
// ********** 5xx Server Error Methods *************
// ErrorInternalServerError writes a 500 Internal Server Error response.
func (c *Context) ErrorInternalServerError(message any) error {
return c.JSON(http.StatusInternalServerError, message)
}
// Abort writes a standardized 500 Internal Server Error response.
func (c *Context) Abort(err error) error {
return c.abortWithError(http.StatusInternalServerError, "Internal Server Error", err)
}
// AbortInternalServerError writes a standardized 500 Internal Server Error response.
func (c *Context) AbortInternalServerError(msg string, err ...error) error {
return c.abortWithStatus(http.StatusInternalServerError, "Internal Server Error", msg, err...)
}
// ErrorNotImplemented writes a 501 Not Implemented response.
func (c *Context) ErrorNotImplemented(message any) error {
return c.JSON(http.StatusNotImplemented, message)
}
// AbortNotImplemented writes a standardized 501 Not Implemented response.
func (c *Context) AbortNotImplemented(msg string, err ...error) error {
return c.abortWithStatus(http.StatusNotImplemented, "Not Implemented", msg, err...)
}
// ErrorBadGateway writes a 502 Bad Gateway response.
func (c *Context) ErrorBadGateway(message any) error {
return c.JSON(http.StatusBadGateway, message)
}
// AbortBadGateway writes a standardized 502 Bad Gateway response.
func (c *Context) AbortBadGateway(msg string, err ...error) error {
return c.abortWithStatus(http.StatusBadGateway, "Bad Gateway", msg, err...)
}
// ErrorServiceUnavailable writes a 503 Service Unavailable response.
func (c *Context) ErrorServiceUnavailable(message any) error {
return c.JSON(http.StatusServiceUnavailable, message)
}
// AbortServiceUnavailable writes a standardized 503 Service Unavailable response.
func (c *Context) AbortServiceUnavailable(msg string, err ...error) error {
return c.abortWithStatus(http.StatusServiceUnavailable, "Service Unavailable", msg, err...)
}
// ErrorGatewayTimeout writes a 504 Gateway Timeout response.
func (c *Context) ErrorGatewayTimeout(message any) error {
return c.JSON(http.StatusGatewayTimeout, message)
}
// AbortGatewayTimeout writes a standardized 504 Gateway Timeout response.
func (c *Context) AbortGatewayTimeout(msg string, err ...error) error {
return c.abortWithStatus(http.StatusGatewayTimeout, "Gateway Timeout", msg, err...)
}
// ErrorHTTPVersionNotSupported writes a 505 HTTP version Not Supported response.
func (c *Context) ErrorHTTPVersionNotSupported(message any) error {
return c.JSON(http.StatusHTTPVersionNotSupported, message)
}
// AbortHTTPVersionNotSupported writes a standardized 505 HTTP version Not Supported response.
func (c *Context) AbortHTTPVersionNotSupported(msg string, err ...error) error {
return c.abortWithStatus(http.StatusHTTPVersionNotSupported, "HTTP version Not Supported", msg, err...)
}
// ErrorVariantAlsoNegotiates writes a 506 Variant Also Negotiates response.
func (c *Context) ErrorVariantAlsoNegotiates(message any) error {
return c.JSON(http.StatusVariantAlsoNegotiates, message)
}
// AbortVariantAlsoNegotiates writes a standardized 506 Variant Also Negotiates response.
func (c *Context) AbortVariantAlsoNegotiates(msg string, err ...error) error {
return c.abortWithStatus(http.StatusVariantAlsoNegotiates, "Variant Also Negotiates", msg, err...)
}
// ErrorInsufficientStorage writes a 507 Insufficient Storage response.
func (c *Context) ErrorInsufficientStorage(message any) error {
return c.JSON(http.StatusInsufficientStorage, message)
}
// AbortInsufficientStorage writes a standardized 507 Insufficient Storage response.
func (c *Context) AbortInsufficientStorage(msg string, err ...error) error {
return c.abortWithStatus(http.StatusInsufficientStorage, "Insufficient Storage", msg, err...)
}
// ErrorLoopDetected writes a 508 Loop Detected response.
func (c *Context) ErrorLoopDetected(message any) error {
return c.JSON(http.StatusLoopDetected, message)
}
// AbortLoopDetected writes a standardized 508 Loop Detected response.
func (c *Context) AbortLoopDetected(msg string, err ...error) error {
return c.abortWithStatus(http.StatusLoopDetected, "Loop Detected", msg, err...)
}
// ErrorNotExtended writes a 510 Not Extended response.
func (c *Context) ErrorNotExtended(message any) error {
return c.JSON(http.StatusNotExtended, message)
}
// AbortNotExtended writes a standardized 510 Not Extended response.
func (c *Context) AbortNotExtended(msg string, err ...error) error {
return c.abortWithStatus(http.StatusNotExtended, "Not Extended", msg, err...)
}
// ErrorNetworkAuthenticationRequired writes a 511 Network Authentication Required response.
func (c *Context) ErrorNetworkAuthenticationRequired(message any) error {
return c.JSON(http.StatusNetworkAuthenticationRequired, message)
}
// AbortNetworkAuthenticationRequired writes a standardized 511 Network Authentication Required response.
func (c *Context) AbortNetworkAuthenticationRequired(msg string, err ...error) error {
return c.abortWithStatus(http.StatusNetworkAuthenticationRequired, "Network Authentication Required", msg, err...)
}
// ********** Utility Methods *************
// IsClientError checks if the status code is a 4xx client error.
func IsClientError(code int) bool {
return code >= 400 && code < 500
}
// IsServerError checks if the status code is a 5xx server error.
func IsServerError(code int) bool {
return code >= 500 && code < 600
}
// IsError checks if the status code represents an error (4xx or 5xx).
func IsError(code int) bool {
return IsClientError(code) || IsServerError(code)
}