forked from jkaninda/okapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenapi.go
More file actions
2096 lines (1871 loc) · 58.1 KB
/
Copy pathopenapi.go
File metadata and controls
2096 lines (1871 loc) · 58.1 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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 (
"crypto/sha256"
"fmt"
"log/slog"
"net/http"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"github.com/getkin/kin-openapi/openapi3"
goutils "github.com/jkaninda/go-utils"
)
const (
constInt = "int"
constUint = "uint"
constInt64 = "int64"
constInt32 = "int32"
constFloat = "float"
constFloat64 = "float64"
constDouble = "double"
constDateTime = "date-time"
constDate = "date"
constUUID = "uuid"
constBool = "bool"
constString = "string"
constEnum = "enum"
)
// RouteOption defines a function type that modifies a Route's documentation properties
type RouteOption func(*Route)
// OpenAPI contains configuration for generating OpenAPI/Swagger documentation.
// It includes metadata about the API and its documentation.
type OpenAPI struct {
Title string // Title of the API
Version string // Version of the API
Servers Servers // List of server URLs where the API is hosted
License License // License information for the API
Contact Contact // Contact information for the API maintainers
// SecuritySchemes defines security schemes for the OpenAPI specification.
SecuritySchemes SecuritySchemes
ExternalDocs *ExternalDocs
ComponentSchemas map[string]*SchemaInfo
}
type SecuritySchemes []SecurityScheme
type SecurityScheme struct {
Extensions map[string]any `json:"-" yaml:"-"`
Origin *Origin `json:"__origin__,omitempty" yaml:"__origin__,omitempty"`
Name string
// Type string // "http", "oauth2", "apiKey"
Type string
// Scheme string // "basic", "bearer", etc.
Scheme string
BearerFormat string
// In string // "header", "query", "cookie"
In string
Flows *OAuthFlows
Description string
}
type ExternalDocs struct {
Extensions map[string]any `json:"-" yaml:"-"`
Origin *Origin `json:"__origin__,omitempty" yaml:"__origin__,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
URL string `json:"url,omitempty" yaml:"url,omitempty"`
}
type Origin struct {
Key *Location `json:"key,omitempty" yaml:"key,omitempty"`
Fields map[string]Location `json:"fields,omitempty" yaml:"fields,omitempty"`
}
type Location struct {
Line int `json:"line,omitempty" yaml:"line,omitempty"`
Column int `json:"column,omitempty" yaml:"column,omitempty"`
}
type OAuthFlow struct {
AuthorizationURL string
TokenURL string
RefreshURL string
Scopes map[string]string
}
type OAuthFlows struct {
Implicit *OAuthFlow
Password *OAuthFlow
ClientCredentials *OAuthFlow
AuthorizationCode *OAuthFlow
}
type SecurityRequirement map[string][]string // SchemeName -> Scopes
// License contains license information for the API.
// It follows the OpenAPI specification format.
type License struct {
Extensions map[string]any `json:"-" yaml:"-"` // Custom extensions not part of OpenAPI spec
Name string `json:"name" yaml:"name"` // Required license name (e.g., "MIT")
URL string `json:"url,omitempty" yaml:"url,omitempty"` // Optional URL to the license
}
// Servers is a list of Server objects representing API server locations
type Servers []Server
// Server represents an API server location where the API is hosted
type Server struct {
Extensions map[string]any `json:"-" yaml:"-"`
// Server URL (e.g., "https://api.example.com/v1")
URL string `json:"url" yaml:"url"`
// Optional server description
Description string `json:"description,omitempty" yaml:"description,omitempty"`
}
// Contact contains contact information for the API maintainers
type Contact struct {
Extensions map[string]any `json:"-" yaml:"-"` // Custom extensions not part of OpenAPI spec
Name string `json:"name,omitempty" yaml:"name,omitempty"` // Optional contact name
URL string `json:"url,omitempty" yaml:"url,omitempty"` // Optional contact URL
Email string `json:"email,omitempty" yaml:"email,omitempty"` // Optional contact email
}
// fieldInfo holds information about a struct field
type fieldInfo struct {
field reflect.StructField
required bool
description string
}
// ToOpenAPI converts License to openapi3.License.
// It transforms the custom License type to the format expected by the openapi3 package.
func (l License) ToOpenAPI() *openapi3.License {
license := &openapi3.License{
Name: l.Name,
URL: l.URL,
}
// Copy any extensions to the target license object
for k, v := range l.Extensions {
license.Extensions[k] = v
}
return license
}
// ToOpenAPI converts Servers to openapi3.Servers.
// It transforms the custom Servers type to the format expected by the openapi3 package.
func (s Servers) ToOpenAPI() openapi3.Servers {
servers := make(openapi3.Servers, 0, len(s))
for _, srv := range s {
server := &openapi3.Server{
URL: srv.URL,
Description: srv.Description,
}
if len(srv.Extensions) > 0 {
for k, v := range srv.Extensions {
server.Extensions[k] = v
}
}
servers = append(servers, server)
}
return servers
}
// ToOpenAPISpec converts OpenAPI to *openapi3.T.
// It transforms the custom OpenAPI configuration to a complete OpenAPI specification object.
func (o OpenAPI) ToOpenAPISpec() *openapi3.T {
return &openapi3.T{
Info: &openapi3.Info{
Title: o.Title,
Version: o.Version,
License: o.License.ToOpenAPI(),
Contact: o.Contact.ToOpenAPI(),
},
Servers: o.Servers.ToOpenAPI(),
Components: &openapi3.Components{
SecuritySchemes: o.SecuritySchemes.ToOpenAPI(),
},
}
}
func (ss SecuritySchemes) ToOpenAPI() openapi3.SecuritySchemes {
result := make(openapi3.SecuritySchemes)
for _, s := range ss {
result[s.Name] = &openapi3.SecuritySchemeRef{
Value: &openapi3.SecurityScheme{
Extensions: s.Extensions,
Origin: s.Origin.ToOpenAPI(),
Type: s.Type,
Name: s.Name,
Scheme: s.Scheme,
BearerFormat: s.BearerFormat,
Flows: s.Flows.ToOpenAPI(),
In: s.In,
Description: s.Description,
},
}
}
return result
}
func (l *Location) ToOpenAPI() openapi3.Location {
if l == nil {
return openapi3.Location{}
}
return openapi3.Location{
Line: l.Line,
Column: l.Column,
}
}
func (o *Origin) ToOpenAPI() *openapi3.Origin {
if o == nil {
return nil
}
origin := &openapi3.Origin{}
if o.Key != nil {
origin.Key = &openapi3.Location{
Line: o.Key.Line,
Column: o.Key.Column,
}
}
if len(o.Fields) > 0 {
origin.Fields = make(map[string]openapi3.Location)
for k, v := range o.Fields {
origin.Fields[k] = v.ToOpenAPI()
}
}
return origin
}
func (e *ExternalDocs) ToOpenAPI() *openapi3.ExternalDocs {
if e == nil {
return nil
}
doc := &openapi3.ExternalDocs{
Description: e.Description,
URL: e.URL,
}
for k, v := range e.Extensions {
doc.Extensions[k] = v
}
return doc
}
func (f *OAuthFlow) ToOpenAPI() *openapi3.OAuthFlow {
if f == nil {
return nil
}
return &openapi3.OAuthFlow{
AuthorizationURL: f.AuthorizationURL,
TokenURL: f.TokenURL,
RefreshURL: f.RefreshURL,
Scopes: f.Scopes,
}
}
func (flows *OAuthFlows) ToOpenAPI() *openapi3.OAuthFlows {
if flows == nil {
return nil
}
return &openapi3.OAuthFlows{
Implicit: flows.Implicit.ToOpenAPI(),
Password: flows.Password.ToOpenAPI(),
ClientCredentials: flows.ClientCredentials.ToOpenAPI(),
AuthorizationCode: flows.AuthorizationCode.ToOpenAPI(),
}
}
// ToOpenAPI converts Contact to openapi3.Contact.
// It transforms the custom Contact type to the format expected by the openapi3 package.
func (c Contact) ToOpenAPI() *openapi3.Contact {
contact := &openapi3.Contact{
Name: c.Name,
URL: c.URL,
Email: c.Email,
}
for k, v := range c.Extensions {
contact.Extensions[k] = v
}
return contact
}
// SchemaInfo holds additional information about a schema for better naming.
// It's used when generating OpenAPI schemas from Go types.
type SchemaInfo struct {
Schema *openapi3.SchemaRef
TypeName string
Package string
}
// Doc creates and returns a new DocBuilder instance for chaining documentation options.
func Doc() *DocBuilder {
return &DocBuilder{}
}
// DocBuilder helps construct a list of RouteOption functions in a fluent, chainable way.
type DocBuilder struct {
options []RouteOption
}
// RequestBody adds a request body schema to the route documentation using the provided value.
func (b *DocBuilder) RequestBody(v any) *DocBuilder {
b.options = append(b.options, DocRequestBody(v))
return b
}
// Response registers a response schema for the route's OpenAPI documentation.
// It can be used in two ways:
// 1. DocResponse(status int, value any) - Defines a response schema for the specified HTTP status code (e.g., 200, 201, 400).
// 2. DocResponse(value any) - Shorthand for DocResponse(200, value).
//
// Examples:
//
// DocResponse(201, CreatedResponse{}) // Response for 201 Created
// DocResponse(400, ErrorResponse{}) // Response for 400 Bad Request
// DocResponse(Response{}) // Response: assumes status 200
func (b *DocBuilder) Response(statusOrValue any, vOptional ...any) *DocBuilder {
b.options = append(b.options, DocResponse(statusOrValue, vOptional...))
return b
}
// ErrorResponse defines an error response schema for a specific HTTP status code
// in the route's OpenAPI documentation.
// Deprecated: This function is deprecated in favor of Response(status, v).
//
// Parameters:
// - status: the HTTP status code (e.g., 400, 404, 500).
// - v: a Go value (e.g., a struct instance) whose type will be used to generate
// the OpenAPI schema for the error response.
func (b *DocBuilder) ErrorResponse(status int, v any) *DocBuilder {
b.options = append(b.options, DocResponse(status, v))
return b
}
// Summary adds a short summary description to the route documentation.
func (b *DocBuilder) Summary(summary string) *DocBuilder {
b.options = append(b.options, Summary(summary))
return b
}
// OperationId sets a unique identifier for the operation in the OpenAPI documentation.
func (b *DocBuilder) OperationId(operationId string) *DocBuilder {
b.options = append(b.options, OperationId(operationId))
return b
}
// Description adds a description to the route documentation.
func (b *DocBuilder) Description(description string) *DocBuilder {
b.options = append(b.options, Description(description))
return b
}
// Tags adds one or more tags to the route documentation for categorization.
func (b *DocBuilder) Tags(tags ...string) *DocBuilder {
b.options = append(b.options, Tags(tags...))
return b
}
// BearerAuth marks the route as requiring Bearer token authentication.
func (b *DocBuilder) BearerAuth() *DocBuilder {
b.options = append(b.options, DocBearerAuth())
return b
}
// Deprecated marks the route as deprecated
func (b *DocBuilder) Deprecated() *DocBuilder {
b.options = append(b.options, Deprecated())
return b
}
// PathParam adds a documented path parameter to the route.
// name: parameter name
// typ: parameter type (e.g., "string", "int")
// desc: parameter description
func (b *DocBuilder) PathParam(name, typ, desc string) *DocBuilder {
b.options = append(b.options, DocPathParam(name, typ, desc))
return b
}
// PathParamWithDefault adds a documented path parameter to the route.
// name: parameter name
// typ: parameter type (e.g., "string", "int")
// desc: parameter description
// defvalue: default value to use
func (b *DocBuilder) PathParamWithDefault(name, typ, desc string, defvalue any) *DocBuilder {
b.options = append(b.options, DocPathParamWithDefault(name, typ, desc, defvalue))
return b
}
// QueryParam adds a documented query parameter to the route.
// name: parameter name
// typ: parameter type (e.g., "string", "int")
// desc: parameter description
// required: whether the parameter is required
func (b *DocBuilder) QueryParam(name, typ, desc string, required bool) *DocBuilder {
b.options = append(b.options, DocQueryParam(name, typ, desc, required))
return b
}
// QueryParamWithDefault adds a documented query parameter to the route with default.
// name: parameter name
// typ: parameter type (e.g., "string", "int")
// desc: parameter description
// required: whether the parameter is required
// defvalue: default value to use
func (b *DocBuilder) QueryParamWithDefault(name, typ, desc string, required bool, defvalue any) *DocBuilder {
b.options = append(b.options, DocQueryParamWithDefault(name, typ, desc, required, defvalue))
return b
}
// Header adds a documented header to the route.
// name: header name
// typ: header value type (e.g., "string", "int")
// desc: header description
// required: whether the header is required
func (b *DocBuilder) Header(name, typ, desc string, required bool) *DocBuilder {
b.options = append(b.options, DocHeader(name, typ, desc, required))
return b
}
// HeaderWithDefault adds a documented header to the route with default.
// name: header name
// typ: header value type (e.g., "string", "int")
// desc: header description
// required: whether the header is required
// defvalue: default value to use
func (b *DocBuilder) HeaderWithDefault(name, typ, desc string, required bool, defvalue any) *DocBuilder {
b.options = append(b.options, DocHeaderWithDefault(name, typ, desc, required, defvalue))
return b
}
// ResponseHeader adds a response header to the route documentation
// name: header name
// typ: header value type (e.g., "string", "int")
// desc: header description, optional
func (b *DocBuilder) ResponseHeader(name, typ string, desc ...string) *DocBuilder {
b.options = append(b.options, DocResponseHeader(name, typ, desc...))
return b
}
// Hide marks the route to be excluded from OpenAPI documentation.
func (b *DocBuilder) Hide() *DocBuilder {
b.options = append(b.options, Hide())
return b
}
// Build returns a single RouteOption composed of all accumulated documentation options.
// This method is intended to be passed directly to route registration functions.
//
// Example:
//
// okapi.Get("/books", handler, okapi.Doc().response(Book{}).Summary("List books").Build())
func (b *DocBuilder) Build() RouteOption {
return b.AsOption()
}
// AsOption returns a single RouteOption by merging all accumulated documentation options.
// This is functionally equivalent to Build(), and exists for naming flexibility and readability.
//
// You can use either Build() or AsOption(), depending on what best fits your code style.
//
// Example:
//
// okapi.Get("/books", handler, okapi.Doc().response(Book{}).AsOption())
func (b *DocBuilder) AsOption() RouteOption {
return func(r *Route) {
for _, opt := range b.options {
opt(r)
}
}
}
// ptr is a helper function that returns a pointer to any value
func ptr[T any](v T) *T { return &v }
// DocSummary sets a short summary description for the route
func DocSummary(summary string) RouteOption {
return Summary(summary)
}
// DocHide marks the route to be excluded from OpenAPI documentation.
func DocHide() RouteOption {
return Hide()
}
func DocOperationId(operationId string) RouteOption {
return OperationId(operationId)
}
// DocDescription sets a description for the route
func DocDescription(description string) RouteOption {
return Description(description)
}
// Hide marks the route to be excluded from OpenAPI documentation.
func Hide() RouteOption {
return func(r *Route) {
r.hidden = true
}
}
// OperationId sets a unique identifier for the operation in the OpenAPI documentation.
func OperationId(operationId string) RouteOption {
return func(r *Route) {
r.operationId = operationId
}
}
// Summary sets a short summary description for the route
func Summary(summary string) RouteOption {
return func(r *Route) {
r.summary = summary
}
}
// Description adds a description to the route documentation.
func Description(description string) RouteOption {
return func(route *Route) {
route.description = description
}
}
// DocPathParam adds a path parameter to the route documentation
// name: parameter name
// typ: parameter type (e.g., "string", "int", "uuid")
// desc: parameter description
func DocPathParam(name, typ, desc string) RouteOption {
return DocPathParamWithDefault(name, typ, desc, nil)
}
// DocPathParamWithDefault adds a path parameter to the route documentation
// name: parameter name
// typ: parameter type (e.g., "string", "int", "uuid")
// desc: parameter description
// defvalue: default value to use.
func DocPathParamWithDefault(name, typ, desc string, defvalue any) RouteOption {
return func(r *Route) {
var schema *openapi3.SchemaRef
// accept custom schema
if sch, ok := defvalue.(*openapi3.SchemaRef); ok {
schema = sch
} else {
schema = getSchemaForType(typ)
if defvalue != nil {
// special handling for enum default
dv := reflect.ValueOf(defvalue)
if strings.ToLower(typ) == constEnum && dv.Kind() == reflect.Slice {
enumvals := make([]any, dv.Len())
for i := 0; i < dv.Len(); i++ {
enumvals[i] = dv.Index(i).Interface()
}
schema.Value.Enum = enumvals
} else {
schema.Value.Default = defvalue
}
}
}
r.pathParams = append(r.pathParams, &openapi3.ParameterRef{
Value: &openapi3.Parameter{
Name: name,
In: "path",
Required: true,
Schema: schema,
Description: desc,
},
})
}
}
// docAutoPathParams automatically extracts path parameters from the route path
// and adds them to the documentation.
// It skips parameters that are already defined.
func docAutoPathParams() RouteOption {
return func(r *Route) {
pathParams := extractPathParams(r.docPath)
for _, param := range pathParams {
// Check if parameter already exists to avoid duplicates
exists := false
for _, existing := range r.pathParams {
if existing.Value.Name == param.Value.Name {
exists = true
break
}
}
if !exists {
r.pathParams = append(r.pathParams, param)
}
}
}
}
// DocQueryParam adds a query parameter to the route documentation
// name: parameter name
// typ: parameter type (e.g., "string", "int")
// desc: parameter description
// required: whether the parameter is required
func DocQueryParam(name, typ, desc string, required bool) RouteOption {
return DocQueryParamWithDefault(name, typ, desc, required, nil)
}
// DocQueryParamWithDefault adds a query parameter to the route documentation (with default if provided)
// name: parameter name
// typ: parameter type (e.g., "string", "int")
// desc: parameter description
// required: whether the parameter is required
// defvalue: default value to use
func DocQueryParamWithDefault(name, typ, desc string, required bool, defvalue any) RouteOption {
return func(r *Route) {
var schema *openapi3.SchemaRef
// accept custom schema
if sch, ok := defvalue.(*openapi3.SchemaRef); ok {
schema = sch
} else {
schema = getSchemaForType(typ)
if defvalue != nil {
// special handling for enum default
dv := reflect.ValueOf(defvalue)
if strings.ToLower(typ) == constEnum && dv.Kind() == reflect.Slice {
enumvals := make([]any, dv.Len())
for i := 0; i < dv.Len(); i++ {
enumvals[i] = dv.Index(i).Interface()
}
schema.Value.Enum = enumvals
} else {
schema.Value.Default = defvalue
}
}
}
r.queryParams = append(r.queryParams, &openapi3.ParameterRef{
Value: &openapi3.Parameter{
Name: name,
In: "query",
Required: required,
Schema: schema,
Description: desc,
},
})
}
}
// DocHeader adds a header parameter to the route documentation
// name: header name
// typ: header value type (e.g., "string", "int")
// desc: header description
// required: whether the header is required
func DocHeader(name, typ, desc string, required bool) RouteOption {
return DocHeaderWithDefault(name, typ, desc, required, nil)
}
// DocHeaderWithDefault adds a header parameter to the route documentation with default (if provided)
// name: header name
// typ: header value type (e.g., "string", "int")
// desc: header description
// required: whether the header is required
// defvalue: default value to use
func DocHeaderWithDefault(name, typ, desc string, required bool, defvalue any) RouteOption {
return func(r *Route) {
var schema *openapi3.SchemaRef
// accept custom schema
if sch, ok := defvalue.(*openapi3.SchemaRef); ok {
schema = sch
} else {
schema = getSchemaForType(typ)
if defvalue != nil {
// special handling for enum default
dv := reflect.ValueOf(defvalue)
if strings.ToLower(typ) == constEnum && dv.Kind() == reflect.Slice {
enumvals := make([]any, dv.Len())
for i := 0; i < dv.Len(); i++ {
enumvals[i] = dv.Index(i).Interface()
}
schema.Value.Enum = enumvals
} else {
schema.Value.Default = defvalue
}
}
}
r.headers = append(r.headers, &openapi3.ParameterRef{
Value: &openapi3.Parameter{
Name: name,
In: "header",
Required: required,
Schema: schema,
Description: desc,
},
})
}
}
// DocTag adds a single tag to categorize the route
func DocTag(tag string) RouteOption {
return Tag(tag)
}
// DocTags adds multiple tags to categorize the route
func DocTags(tags ...string) RouteOption {
return Tags(tags...)
}
// DocResponseHeader adds a response header to the route documentation
// name: header name
// typ: header value type (e.g., "string", "int")
// desc: header description, optional
func DocResponseHeader(name, typ string, desc ...string) RouteOption {
return func(r *Route) {
schema := getSchemaForType(typ)
description := ""
// Initialize responseHeaders map if it doesn't exist
if r.responseHeaders == nil {
r.responseHeaders = make(map[string]*openapi3.HeaderRef)
}
if len(desc) != 0 {
description = desc[0]
}
r.responseHeaders[name] = &openapi3.HeaderRef{
Value: &openapi3.Header{
Parameter: openapi3.Parameter{
Description: description,
Required: true,
Schema: schema,
},
},
}
}
}
// DocResponse registers a response schema for the route's OpenAPI documentation.
// It can be used in two ways:
// 1. DocResponse(status int, value any) - Defines a response schema for the specified HTTP status code (e.g., 200, 201, 400).
// 2. DocResponse(value any) - Shorthand for DocResponse(200, value).
//
// Examples:
//
// DocResponse(201, CreatedResponse{}) // response for 201 Created
// DocResponse(400, ErrorResponse{}) // response for 400 Bad request
// DocResponse(response{}) // response: assumes status 200
func DocResponse(statusOrValue any, vOptional ...any) RouteOption {
return func(doc *Route) {
switch val := statusOrValue.(type) {
case int:
// usage: DocResponse(200, value)
if len(vOptional) == 0 || vOptional[0] == nil {
return
}
doc.responses[val] = reflectToSchemaWithInfo(vOptional[0]).Schema
default:
// usage: DocResponse(value)
if val == nil {
return
}
doc.responses[200] = reflectToSchemaWithInfo(val).Schema
}
}
}
// DocErrorResponse defines an error response schema for a specific HTTP status code
// in the route's OpenAPI documentation.
// Deprecated: This function is deprecated in favor of DocResponse(status, v).
//
// Parameters:
// - status: the HTTP status code (e.g., 400, 404, 500).
// - v: a Go value (e.g., a struct instance) whose type will be used to generate
// the OpenAPI schema for the error response.
//
// Returns:
// - A RouteOption function that adds the error schema to the route's documentation.
func DocErrorResponse(status int, v any) RouteOption {
return func(doc *Route) {
if v == nil {
return
}
// Generate a schema from the provided Go value and assign it to the error response
doc.responses[status] = reflectToSchemaWithInfo(v).Schema
}
}
// DocRequestBody defines the request body schema for the route
// v: a Go value whose type will be used to generate the request schema
func DocRequestBody(v any) RouteOption {
return func(doc *Route) {
if v == nil {
return
}
doc.request = reflectToSchemaWithInfo(v).Schema
}
}
// Tag adds a single tag to categorize the route
func Tag(tag string) RouteOption {
return func(r *Route) {
r.tags = append(r.tags, tag)
}
}
// Tags adds multiple tags to categorize the route
func Tags(tags ...string) RouteOption {
return func(doc *Route) {
doc.tags = append(doc.tags, tags...)
}
}
// Request registers the request schema for a route.
// The provided value must be a struct or a pointer to a struct.
//
// This schema is used for both OpenAPI documentation and request validation.
//
// Field mapping rules:
// - Request body: A field named `Body`, or a field tagged with `json:"body"`, is treated as the request body.
// - Path parameters: Fields tagged with `path:"name"` or `param:"name"` are treated as path parameters.
// - Query parameters: Fields tagged with `query:"name"` are treated as query parameters.
// - Headers: Fields tagged with `header:"name"` are treated as HTTP headers.
// - Cookies: Fields tagged with `cookie:"name"` are treated as HTTP cookies.
// - Any remaining fields are treated as general request metadata or ignored if not applicable.
func Request(v any) RouteOption {
return func(r *Route) {
if v != nil {
r.generateRequestSchema(v)
}
}
}
// Response registers the response schema for a route.
// The provided value must be a struct or a pointer to a struct.
//
// This schema is used for OpenAPI documentation and response representation.
//
// Field mapping rules:
// - Status code: A field named `Status` is interpreted as the HTTP status code (default: 200 if omitted).
// - Response body: A field named `Body`, or a field tagged with `json:",inline"`, is treated as the response body.
// - Headers: Fields tagged with `header:"name"` are treated as HTTP response headers.
// - Cookies: Fields tagged with `cookie:"name"` are treated as HTTP cookies.
// - Any remaining fields are treated as general response metadata or ignored if not applicable.
//
// Example:
//
// type CreateUserResponse struct {
// Status int `json:"status"`
// Body User `json:"body"`
// Trace string `header:"X-Trace-ID"`
// SessionId string `cookie:"session_id"`
// }
func Response(v any) RouteOption {
return func(r *Route) {
if v != nil {
r.generateResponseSchema(v)
}
}
}
// WithIO registers both request and response schemas for a route in one call.
// It is a convenience helper that combines Request and Response.
func WithIO(req any, res any) RouteOption {
return func(r *Route) {
if req != nil {
r.generateRequestSchema(req)
}
if res != nil {
r.generateResponseSchema(res)
}
}
}
// DocBearerAuth marks the route as requiring Bearer token authentication
func DocBearerAuth() RouteOption {
return func(doc *Route) {
doc.bearerAuth = true
}
}
// DocBasicAuth marks the route as requiring Basic authentication
func DocBasicAuth() RouteOption {
return func(doc *Route) {
doc.basicAuth = true
}
}
// DocDeprecated marks the route as deprecated
func DocDeprecated() RouteOption {
return Deprecated()
}
// Deprecated marks the route as deprecated
func Deprecated() RouteOption {
return func(doc *Route) {
doc.deprecated = true
}
}
func withSecurity(security []map[string][]string) RouteOption {
return func(r *Route) {
r.security = security
}
}
// buildOpenAPISpec constructs the complete OpenAPI specification document
// by aggregating all the route documentation into a single OpenAPI 3.0 spec
func (o *Okapi) buildOpenAPISpec() {
spec := &openapi3.T{
OpenAPI: openApiVersion,
Info: &openapi3.Info{
Title: o.openAPI.Title,
Version: o.openAPI.Version,
License: o.openAPI.License.ToOpenAPI(),
Contact: o.openAPI.Contact.ToOpenAPI(),
},
Paths: &openapi3.Paths{},
Servers: o.openAPI.Servers.ToOpenAPI(),
Components: &openapi3.Components{
SecuritySchemes: o.openAPI.SecuritySchemes.ToOpenAPI(),
Schemas: make(openapi3.Schemas),
},
ExternalDocs: o.openAPI.ExternalDocs.ToOpenAPI(),
}
if len(o.openAPI.SecuritySchemes) == 0 && o.hasBearerAuth() {
spec.Components.SecuritySchemes = openapi3.SecuritySchemes{
"BearerAuth": &openapi3.SecuritySchemeRef{
Value: &openapi3.SecurityScheme{
Type: "http",
Scheme: "bearer",
BearerFormat: "JWT",
},
},
}
}
if len(o.openAPI.SecuritySchemes) == 0 && o.hasBasicAuth() {
spec.Components.SecuritySchemes = openapi3.SecuritySchemes{
"BasicAuth": &openapi3.SecuritySchemeRef{
Value: &openapi3.SecurityScheme{
Type: "http",
Scheme: "basic",
},
},
}
}
// Initialize schema registry for reusable components
schemaRegistry := make(map[string]*SchemaInfo)
// Start with registered ones first
for name, sinfo := range o.openAPI.ComponentSchemas {
schemaRegistry[name] = sinfo
spec.Components.Schemas[name] = sinfo.Schema
}
// Process all registered routes
for _, r := range o.routes {
// If route is disabled ignore it
if r.disabled || r.hidden {
continue
}
// Auto-extract path parameters if none are defined
if len(r.pathParams) == 0 {
docAutoPathParams()(r)
}
if len(r.operationId) == 0 {
if len(r.summary) != 0 {
r.operationId = goutils.Slug(r.summary)
}
}
item := spec.Paths.Value(r.Path)
if item == nil {
item = &openapi3.PathItem{}
spec.Paths.Set(r.Path, item)
}
op := &openapi3.Operation{
OperationID: r.operationId,
Summary: r.summary,
Description: r.description,
Tags: goutils.RemoveDuplicates(r.tags), // Remove duplicates in tags
Parameters: append(append(r.pathParams, r.queryParams...), r.headers...),
Responses: &openapi3.Responses{},
Deprecated: r.deprecated,
}