-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathoapi_validate_example_test.go
More file actions
841 lines (681 loc) · 26.5 KB
/
oapi_validate_example_test.go
File metadata and controls
841 lines (681 loc) · 26.5 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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
package nethttpmiddleware_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
middleware "github.com/oapi-codegen/nethttp-middleware"
)
func ExampleOapiRequestValidatorWithOptions() {
rawSpec := `
openapi: "3.0.0"
info:
version: 1.0.0
title: TestServer
servers:
- url: http://example.com/
paths:
/resource:
post:
operationId: createResource
responses:
'204':
description: No content
requestBody:
required: true
content:
application/json:
schema:
properties:
name:
type: string
additionalProperties: false
/protected_resource:
get:
operationId: getProtectedResource
security:
- BearerAuth:
- someScope
responses:
'204':
description: no content
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
`
must := func(err error) {
if err != nil {
panic(err)
}
}
use := func(r *http.ServeMux, middlewares ...func(next http.Handler) http.Handler) http.Handler {
var s http.Handler
s = r
for _, mw := range middlewares {
s = mw(s)
}
return s
}
logResponseBody := func(rr *httptest.ResponseRecorder) {
if rr.Result().Body != nil {
data, _ := io.ReadAll(rr.Result().Body)
if len(data) > 0 {
fmt.Printf("Response body: %s", data)
}
}
}
spec, err := openapi3.NewLoader().LoadFromData([]byte(rawSpec))
must(err)
// NOTE that we need to make sure that the `Servers` aren't set, otherwise the OpenAPI validation middleware will validate that the `Host` header (of incoming requests) are targeting known `Servers` in the OpenAPI spec
// See also: Options#SilenceServersWarning
spec.Servers = nil
router := http.NewServeMux()
router.HandleFunc("/resource", func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s /resource was called\n", r.Method)
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusNoContent)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
})
router.HandleFunc("/protected_resource", func(w http.ResponseWriter, r *http.Request) {
// NOTE that we're setting up our `authenticationFunc` (below) to /never/ allow any requests in - so if we get a response from this endpoint, our `authenticationFunc` hasn't correctly worked
if r.Method == http.MethodGet {
w.WriteHeader(http.StatusNoContent)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
})
authenticationFunc := func(ctx context.Context, ai *openapi3filter.AuthenticationInput) error {
fmt.Printf("`AuthenticationFunc` was called for securitySchemeName=%s\n", ai.SecuritySchemeName)
return fmt.Errorf("this check always fails - don't let anyone in!")
}
// create middleware
mw := middleware.OapiRequestValidatorWithOptions(spec, &middleware.Options{
Options: openapi3filter.Options{
AuthenticationFunc: authenticationFunc,
},
})
// then wire it in
server := use(router, mw)
// ================================================================================
fmt.Println("# A request that is malformed is rejected with HTTP 400 Bad Request (with no request body)")
req, err := http.NewRequest(http.MethodPost, "/resource", bytes.NewReader(nil))
must(err)
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 400\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// ================================================================================
fmt.Println("# A request that is malformed is rejected with HTTP 400 Bad Request (because an invalid property is sent, and we have `additionalProperties: false`)")
body := map[string]string{
"invalid": "not expected",
}
data, err := json.Marshal(body)
must(err)
req, err = http.NewRequest(http.MethodPost, "/resource", bytes.NewReader(data))
must(err)
req.Header.Set("Content-Type", "application/json")
rr = httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 400\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// ================================================================================
fmt.Println("# A request with an invalid HTTP method, to a valid path, is rejected with an HTTP 405 Method Not Allowed")
body = map[string]string{
"invalid": "not expected",
}
data, err = json.Marshal(body)
must(err)
req, err = http.NewRequest(http.MethodPatch, "/resource", bytes.NewReader(data))
must(err)
req.Header.Set("Content-Type", "application/json")
rr = httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 405\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// ================================================================================
fmt.Println("# A request that is well-formed is passed through to the Handler")
body = map[string]string{
"name": "Jamie",
}
data, err = json.Marshal(body)
must(err)
req, err = http.NewRequest(http.MethodPost, "/resource", bytes.NewReader(data))
must(err)
req.Header.Set("Content-Type", "application/json")
rr = httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 204\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// ================================================================================
fmt.Println("# A request to an authenticated endpoint must go through an `AuthenticationFunc`, and if it fails, an HTTP 401 is returned")
req, err = http.NewRequest(http.MethodGet, "/protected_resource", nil)
must(err)
rr = httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 401\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// Output:
// # A request that is malformed is rejected with HTTP 400 Bad Request (with no request body)
// Received an HTTP 400 response. Expected HTTP 400
// Response body: request body has an error: value is required but missing
//
// # A request that is malformed is rejected with HTTP 400 Bad Request (because an invalid property is sent, and we have `additionalProperties: false`)
// Received an HTTP 400 response. Expected HTTP 400
// Response body: request body has an error: doesn't match schema: property "invalid" is unsupported
//
// # A request with an invalid HTTP method, to a valid path, is rejected with an HTTP 405 Method Not Allowed
// Received an HTTP 405 response. Expected HTTP 405
// Response body: method not allowed
//
// # A request that is well-formed is passed through to the Handler
// POST /resource was called
// Received an HTTP 204 response. Expected HTTP 204
//
// # A request to an authenticated endpoint must go through an `AuthenticationFunc`, and if it fails, an HTTP 401 is returned
// `AuthenticationFunc` was called for securitySchemeName=BearerAuth
// Received an HTTP 401 response. Expected HTTP 401
// Response body: security requirements failed: this check always fails - don't let anyone in!
}
func ExampleOapiRequestValidatorWithOptions_withErrorHandler() {
rawSpec := `
openapi: "3.0.0"
info:
version: 1.0.0
title: TestServer
servers:
- url: http://example.com/
paths:
/resource:
post:
operationId: createResource
responses:
'204':
description: No content
requestBody:
required: true
content:
application/json:
schema:
properties:
name:
type: string
additionalProperties: false
`
must := func(err error) {
if err != nil {
panic(err)
}
}
use := func(r *http.ServeMux, middlewares ...func(next http.Handler) http.Handler) http.Handler {
var s http.Handler
s = r
for _, mw := range middlewares {
s = mw(s)
}
return s
}
logResponseBody := func(rr *httptest.ResponseRecorder) {
if rr.Result().Body != nil {
data, _ := io.ReadAll(rr.Result().Body)
if len(data) > 0 {
fmt.Printf("Response body: %s", data)
}
}
}
spec, err := openapi3.NewLoader().LoadFromData([]byte(rawSpec))
must(err)
// NOTE that we need to make sure that the `Servers` aren't set, otherwise the OpenAPI validation middleware will validate that the `Host` header (of incoming requests) are targeting known `Servers` in the OpenAPI spec
// See also: Options#SilenceServersWarning
spec.Servers = nil
router := http.NewServeMux()
router.HandleFunc("/resource", func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s /resource was called\n", r.Method)
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusNoContent)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
})
authenticationFunc := func(ctx context.Context, ai *openapi3filter.AuthenticationInput) error {
fmt.Printf("`AuthenticationFunc` was called for securitySchemeName=%s\n", ai.SecuritySchemeName)
return fmt.Errorf("this check always fails - don't let anyone in!")
}
errorHandlerFunc := func(w http.ResponseWriter, message string, statusCode int) {
fmt.Printf("ErrorHandler: An HTTP %d was returned by the middleware with error message: %s\n", statusCode, message)
http.Error(w, "This was rewritten by the ErrorHandler", statusCode)
}
// create middleware
mw := middleware.OapiRequestValidatorWithOptions(spec, &middleware.Options{
Options: openapi3filter.Options{
AuthenticationFunc: authenticationFunc,
},
ErrorHandler: errorHandlerFunc,
})
// then wire it in
server := use(router, mw)
// ================================================================================
fmt.Println("# A request that is malformed is rejected with HTTP 400 Bad Request (with no request body), and is then logged by the ErrorHandler")
req, err := http.NewRequest(http.MethodPost, "/resource", bytes.NewReader(nil))
must(err)
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 400\n", rr.Code)
logResponseBody(rr)
// Output:
// # A request that is malformed is rejected with HTTP 400 Bad Request (with no request body), and is then logged by the ErrorHandler
// ErrorHandler: An HTTP 400 was returned by the middleware with error message: request body has an error: value is required but missing
// Received an HTTP 400 response. Expected HTTP 400
// Response body: This was rewritten by the ErrorHandler
}
func ExampleOapiRequestValidatorWithOptions_withErrorHandlerWithOpts() {
rawSpec := `
openapi: "3.0.0"
info:
version: 1.0.0
title: TestServer
servers:
- url: http://example.com/
paths:
/resource:
post:
operationId: createResource
responses:
'204':
description: No content
requestBody:
required: true
content:
application/json:
schema:
properties:
id:
type: string
minLength: 100
name:
type: string
enum:
- Marcin
additionalProperties: false
/protected_resource:
get:
operationId: getProtectedResource
security:
- BearerAuth:
- someScope
- BasicAuth: []
responses:
'204':
description: no content
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
BasicAuth:
type: http
scheme: basic
`
must := func(err error) {
if err != nil {
panic(err)
}
}
use := func(r *http.ServeMux, middlewares ...func(next http.Handler) http.Handler) http.Handler {
var s http.Handler
s = r
for _, mw := range middlewares {
s = mw(s)
}
return s
}
logResponseBody := func(rr *httptest.ResponseRecorder) {
if rr.Result().Body != nil {
data, _ := io.ReadAll(rr.Result().Body)
if len(data) > 0 {
fmt.Printf("Response body: %s", data)
}
}
}
spec, err := openapi3.NewLoader().LoadFromData([]byte(rawSpec))
must(err)
// NOTE that we need to make sure that the `Servers` aren't set, otherwise the OpenAPI validation middleware will validate that the `Host` header (of incoming requests) are targeting known `Servers` in the OpenAPI spec
// See also: Options#SilenceServersWarning
spec.Servers = nil
router := http.NewServeMux()
router.HandleFunc("/resource", func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s /resource was called\n", r.Method)
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusNoContent)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
})
router.HandleFunc("/protected_resource", func(w http.ResponseWriter, r *http.Request) {
// NOTE that we're setting up our `authenticationFunc` (below) to /never/ allow any requests in - so if we get a response from this endpoint, our `authenticationFunc` hasn't correctly worked
if r.Method == http.MethodGet {
w.WriteHeader(http.StatusNoContent)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
})
authenticationFunc := func(ctx context.Context, ai *openapi3filter.AuthenticationInput) error {
fmt.Printf("`AuthenticationFunc` was called for securitySchemeName=%s\n", ai.SecuritySchemeName)
return fmt.Errorf("this check always fails - don't let anyone in!")
}
errorHandlerFunc := func(ctx context.Context, err error, w http.ResponseWriter, r *http.Request, opts middleware.ErrorHandlerOpts) {
if opts.MatchedRoute == nil {
fmt.Printf("ErrorHandlerWithOpts: An HTTP %d was returned by the middleware with error message: %s\n", opts.StatusCode, err.Error())
// NOTE that you may want to override the default (an HTTP 400 Bad Request) to an HTTP 404 Not Found (or maybe an HTTP 405 Method Not Allowed, depending on what the requested resource was)
http.Error(w, fmt.Sprintf("No route was found (according to ErrorHandlerWithOpts), and we changed the HTTP status code to %d", http.StatusNotFound), http.StatusNotFound)
return
}
switch e := err.(type) {
case *openapi3filter.SecurityRequirementsError:
out := fmt.Sprintf("A SecurityRequirementsError was returned when attempting to authenticate the request to %s %s against %d Security Schemes: %s\n", opts.MatchedRoute.Route.Method, opts.MatchedRoute.Route.Path, len(e.SecurityRequirements), e.Error())
for _, sr := range e.SecurityRequirements {
for k, v := range sr {
out += fmt.Sprintf("- %s: %v\n", k, v)
}
}
fmt.Printf("ErrorHandlerWithOpts: %s\n", out)
http.Error(w, "You're not allowed!", opts.StatusCode)
return
case *openapi3filter.RequestError:
out := fmt.Sprintf("A RequestError was returned when attempting to validate the request to %s %s: %s\n", opts.MatchedRoute.Route.Method, opts.MatchedRoute.Route.Path, e.Error())
if e.RequestBody != nil {
out += "This operation has a request body, which was "
if !e.RequestBody.Required {
out += "not "
}
out += "required\n"
}
if childErr := e.Unwrap(); childErr != nil {
out += "There was a child error, which was "
switch e := childErr.(type) {
case *openapi3.SchemaError:
out += "a SchemaError, which failed to validate on the " + e.SchemaField + " field"
default:
out += "an unknown type (" + reflect.TypeOf(e).String() + ")"
}
}
fmt.Printf("ErrorHandlerWithOpts: %s\n", out)
http.Error(w, "A bad request was made - but I'm not going to tell you where or how", opts.StatusCode)
return
}
http.Error(w, err.Error(), opts.StatusCode)
}
// create middleware
mw := middleware.OapiRequestValidatorWithOptions(spec, &middleware.Options{
Options: openapi3filter.Options{
AuthenticationFunc: authenticationFunc,
},
ErrorHandlerWithOpts: errorHandlerFunc,
})
// then wire it in
server := use(router, mw)
// ================================================================================
fmt.Println("# A request that is malformed is rejected with HTTP 400 Bad Request (with no request body), and is then logged by the ErrorHandlerWithOpts")
req, err := http.NewRequest(http.MethodPost, "/resource", nil)
must(err)
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 400\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// ================================================================================
fmt.Println("# A request that is malformed is rejected with HTTP 400 Bad Request (with an invalid request body), and is then logged by the ErrorHandlerWithOpts")
body := map[string]string{
"id": "not-long-enough",
}
data, err := json.Marshal(body)
must(err)
req, err = http.NewRequest(http.MethodPost, "/resource", bytes.NewReader(data))
must(err)
req.Header.Set("Content-Type", "application/json")
rr = httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 400\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// ================================================================================
fmt.Println("# A request that to an unknown path is rejected with HTTP 404 Not Found, and is then logged by the ErrorHandlerWithOpts")
req, err = http.NewRequest(http.MethodGet, "/not-a-real-path", nil)
must(err)
rr = httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 404\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// ================================================================================
fmt.Println("# A request to an authenticated endpoint must go through an `AuthenticationFunc`, and if it fails, an HTTP 401 is returned")
req, err = http.NewRequest(http.MethodGet, "/protected_resource", nil)
must(err)
rr = httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 401\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// Output:
// # A request that is malformed is rejected with HTTP 400 Bad Request (with no request body), and is then logged by the ErrorHandlerWithOpts
// ErrorHandlerWithOpts: A RequestError was returned when attempting to validate the request to POST /resource: request body has an error: value is required but missing
// This operation has a request body, which was required
// There was a child error, which was an unknown type (*errors.errorString)
// Received an HTTP 400 response. Expected HTTP 400
// Response body: A bad request was made - but I'm not going to tell you where or how
//
// # A request that is malformed is rejected with HTTP 400 Bad Request (with an invalid request body), and is then logged by the ErrorHandlerWithOpts
// ErrorHandlerWithOpts: A RequestError was returned when attempting to validate the request to POST /resource: request body has an error: doesn't match schema: Error at "/id": minimum string length is 100
// Schema:
// {
// "minLength": 100,
// "type": "string"
// }
//
// Value:
// "not-long-enough"
//
// This operation has a request body, which was required
// There was a child error, which was a SchemaError, which failed to validate on the minLength field
// Received an HTTP 400 response. Expected HTTP 400
// Response body: A bad request was made - but I'm not going to tell you where or how
//
// # A request that to an unknown path is rejected with HTTP 404 Not Found, and is then logged by the ErrorHandlerWithOpts
// ErrorHandlerWithOpts: An HTTP 404 was returned by the middleware with error message: no matching operation was found
// Received an HTTP 404 response. Expected HTTP 404
// Response body: No route was found (according to ErrorHandlerWithOpts), and we changed the HTTP status code to 404
//
// # A request to an authenticated endpoint must go through an `AuthenticationFunc`, and if it fails, an HTTP 401 is returned
// `AuthenticationFunc` was called for securitySchemeName=BearerAuth
// `AuthenticationFunc` was called for securitySchemeName=BasicAuth
// ErrorHandlerWithOpts: A SecurityRequirementsError was returned when attempting to authenticate the request to GET /protected_resource against 2 Security Schemes: security requirements failed: this check always fails - don't let anyone in! | this check always fails - don't let anyone in!
// - BearerAuth: [someScope]
// - BasicAuth: []
//
// Received an HTTP 401 response. Expected HTTP 401
// Response body: You're not allowed!
}
func ExampleOapiRequestValidatorWithOptions_withErrorHandlerWithOptsAndMultiError() {
rawSpec := `
openapi: "3.0.0"
info:
version: 1.0.0
title: TestServer
servers:
- url: http://example.com/
paths:
/resource:
post:
operationId: createResource
responses:
'204':
description: No content
requestBody:
required: true
content:
application/json:
schema:
properties:
id:
type: string
minLength: 100
name:
type: string
enum:
- Marcin
additionalProperties: false
`
must := func(err error) {
if err != nil {
panic(err)
}
}
use := func(r *http.ServeMux, middlewares ...func(next http.Handler) http.Handler) http.Handler {
var s http.Handler
s = r
for _, mw := range middlewares {
s = mw(s)
}
return s
}
logResponseBody := func(rr *httptest.ResponseRecorder) {
if rr.Result().Body != nil {
data, _ := io.ReadAll(rr.Result().Body)
if len(data) > 0 {
fmt.Printf("Response body: %s", data)
}
}
}
spec, err := openapi3.NewLoader().LoadFromData([]byte(rawSpec))
must(err)
// NOTE that we need to make sure that the `Servers` aren't set, otherwise the OpenAPI validation middleware will validate that the `Host` header (of incoming requests) are targeting known `Servers` in the OpenAPI spec
// See also: Options#SilenceServersWarning
spec.Servers = nil
router := http.NewServeMux()
router.HandleFunc("/resource", func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s /resource was called\n", r.Method)
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusNoContent)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
})
errorHandlerFunc := func(ctx context.Context, err error, w http.ResponseWriter, r *http.Request, opts middleware.ErrorHandlerOpts) {
if opts.MatchedRoute == nil {
fmt.Printf("ErrorHandlerWithOpts: An HTTP %d was returned by the middleware with error message: %s\n", opts.StatusCode, err.Error())
// NOTE that you may want to override the default (an HTTP 400 Bad Request) to an HTTP 404 Not Found (or maybe an HTTP 405 Method Not Allowed, depending on what the requested resource was)
http.Error(w, fmt.Sprintf("No route was found (according to ErrorHandlerWithOpts), and we changed the HTTP status code to %d", http.StatusNotFound), http.StatusNotFound)
return
}
switch e := err.(type) {
// NOTE that when it's a MultiError, there's more work needed here
case openapi3.MultiError:
var re *openapi3filter.RequestError
if e.As(&re) {
out := fmt.Sprintf("A MultiError was encountered, which contained a RequestError: %s", re)
if re.Err != nil {
out += ", which inside it has a error of type (" + reflect.TypeOf(e).String() + ")"
}
fmt.Printf("ErrorHandlerWithOpts: %s\n", out)
http.Error(w, "There was a bad request", opts.StatusCode)
return
}
var se *openapi3filter.SecurityRequirementsError
if e.As(&se) {
out := fmt.Sprintf("A MultiError was encountered, which contained a SecurityRequirementsError: %s", re)
if len(se.Errors) > 0 {
out += fmt.Sprintf(", which contains %d child errors", len(se.Errors))
}
fmt.Printf("ErrorHandlerWithOpts: %s\n", out)
http.Error(w, "There was an unauthorized request", opts.StatusCode)
return
}
}
http.Error(w, err.Error(), opts.StatusCode)
}
// create middleware
mw := middleware.OapiRequestValidatorWithOptions(spec, &middleware.Options{
Options: openapi3filter.Options{
// make sure that multiple errors in a given request are returned
MultiError: true,
},
ErrorHandlerWithOpts: errorHandlerFunc,
})
// then wire it in
server := use(router, mw)
// ================================================================================
fmt.Println("# A request that is malformed is rejected with HTTP 400 Bad Request (with no request body), and is then logged by the ErrorHandlerWithOpts")
req, err := http.NewRequest(http.MethodPost, "/resource", nil)
must(err)
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 400\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// ================================================================================
fmt.Println("# A request that is malformed is rejected with HTTP 400 Bad Request (with an invalid request body, with multiple issues), and is then logged by the ErrorHandlerWithOpts")
body := map[string]string{
"id": "not-long-enough",
"name": "Jamie",
}
data, err := json.Marshal(body)
must(err)
req, err = http.NewRequest(http.MethodPost, "/resource", bytes.NewReader(data))
must(err)
req.Header.Set("Content-Type", "application/json")
rr = httptest.NewRecorder()
server.ServeHTTP(rr, req)
fmt.Printf("Received an HTTP %d response. Expected HTTP 400\n", rr.Code)
logResponseBody(rr)
fmt.Println()
// Output:
// # A request that is malformed is rejected with HTTP 400 Bad Request (with no request body), and is then logged by the ErrorHandlerWithOpts
// ErrorHandlerWithOpts: A MultiError was encountered, which contained a RequestError: request body has an error: value is required but missing, which inside it has a error of type (openapi3.MultiError)
// Received an HTTP 400 response. Expected HTTP 400
// Response body: There was a bad request
//
// # A request that is malformed is rejected with HTTP 400 Bad Request (with an invalid request body, with multiple issues), and is then logged by the ErrorHandlerWithOpts
// ErrorHandlerWithOpts: A MultiError was encountered, which contained a RequestError: request body has an error: doesn't match schema: Error at "/id": minimum string length is 100
// Schema:
// {
// "minLength": 100,
// "type": "string"
// }
//
// Value:
// "not-long-enough"
// | Error at "/name": value is not one of the allowed values ["Marcin"]
// Schema:
// {
// "enum": [
// "Marcin"
// ],
// "type": "string"
// }
//
// Value:
// "Jamie"
// , which inside it has a error of type (openapi3.MultiError)
// Received an HTTP 400 response. Expected HTTP 400
// Response body: There was a bad request
}