-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiberoapi.go
More file actions
939 lines (817 loc) · 26.4 KB
/
fiberoapi.go
File metadata and controls
939 lines (817 loc) · 26.4 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
package fiberoapi
import (
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"github.com/gofiber/fiber/v2"
"gopkg.in/yaml.v3"
)
// DefaultConfig returns the default configuration
func DefaultConfig() Config {
return Config{
EnableValidation: true,
EnableOpenAPIDocs: true,
OpenAPIDocsPath: "/docs",
OpenAPIJSONPath: "/openapi.json",
OpenAPIYamlPath: "/openapi.yaml",
}
}
// New creates a new OApiApp with optional configuration
func New(app *fiber.App, config ...Config) *OApiApp {
// Use default config if none provided
cfg := DefaultConfig()
if len(config) > 0 {
provided := config[0]
// Merge provided config with defaults
// For boolean fields with true defaults, we need special handling
// We'll only override if the provided config appears to be intentionally configured
// Simple approach: if the provided config has any non-default values,
// we assume the user intended to configure it explicitly
hasExplicitConfig := provided.EnableAuthorization ||
provided.AuthService != nil ||
provided.SecuritySchemes != nil ||
provided.OpenAPIDocsPath != "" ||
provided.OpenAPIJSONPath != "" ||
provided.OpenAPIYamlPath != "" ||
provided.ValidationErrorHandler != nil
// Only override boolean defaults if the config appears to be explicitly set
if hasExplicitConfig {
cfg.EnableValidation = provided.EnableValidation
cfg.EnableOpenAPIDocs = provided.EnableOpenAPIDocs
}
// If no explicit config, keep the defaults (true, true, false)
// Special case: if ValidationErrorHandler is set and boolean fields seem to be using zero values,
// restore defaults since it makes no sense to have a validation error handler without validation
otherExplicitConfig := provided.EnableAuthorization ||
provided.AuthService != nil ||
provided.SecuritySchemes != nil ||
provided.OpenAPIDocsPath != "" ||
provided.OpenAPIJSONPath != "" ||
provided.OpenAPIYamlPath != ""
// Only restore defaults if ALL boolean fields are false (suggesting they weren't explicitly set)
allBooleansAreFalse := !provided.EnableValidation && !provided.EnableOpenAPIDocs && !provided.EnableAuthorization
if provided.ValidationErrorHandler != nil && !otherExplicitConfig && allBooleansAreFalse {
// ValidationErrorHandler is the only explicit config, so restore defaults for boolean fields
cfg.EnableValidation = true // Keep validation enabled - the handler needs it
cfg.EnableOpenAPIDocs = true // Keep docs enabled - default behavior
}
// For EnableAuthorization: only set to true if explicitly provided
if provided.EnableAuthorization {
cfg.EnableAuthorization = provided.EnableAuthorization
}
// Non-boolean fields use the original logic
if provided.OpenAPIDocsPath != "" {
cfg.OpenAPIDocsPath = provided.OpenAPIDocsPath
}
if provided.OpenAPIJSONPath != "" {
cfg.OpenAPIJSONPath = provided.OpenAPIJSONPath
}
if provided.OpenAPIYamlPath != "" {
cfg.OpenAPIYamlPath = provided.OpenAPIYamlPath
}
if provided.AuthService != nil {
cfg.AuthService = provided.AuthService
}
if provided.SecuritySchemes != nil {
cfg.SecuritySchemes = provided.SecuritySchemes
}
if provided.DefaultSecurity != nil {
cfg.DefaultSecurity = provided.DefaultSecurity
}
if provided.ValidationErrorHandler != nil {
cfg.ValidationErrorHandler = provided.ValidationErrorHandler
}
}
oapi := &OApiApp{
f: app,
operations: make([]OpenAPIOperation, 0),
config: cfg,
}
// Automatically setup documentation routes if enabled
if cfg.EnableOpenAPIDocs {
oapi.setupDocsRoutes()
}
return oapi
}
func (o *OApiApp) setupDocsRoutes() {
// Serve OpenAPI JSON specification
o.f.Get(o.Config().OpenAPIJSONPath, func(c *fiber.Ctx) error {
spec := o.GenerateOpenAPISpec()
c.Set("Content-Type", "application/json")
return c.JSON(spec)
})
// Serve OpenAPI YAML specification
o.f.Get(o.Config().OpenAPIYamlPath, func(c *fiber.Ctx) error {
spec, err := o.GenerateOpenAPISpecYAML()
if err != nil {
return err
}
c.Set("Content-Type", "application/yaml")
return c.SendString(spec)
})
// Serve Redoc documentation
o.f.Get(o.Config().OpenAPIDocsPath, func(c *fiber.Ctx) error {
html := generateRedocHTML(o.Config().OpenAPIJSONPath, "API Documentation")
c.Set("Content-Type", "text/html")
return c.SendString(html)
})
// Handle trailing slash redirect
if !strings.HasSuffix(o.Config().OpenAPIDocsPath, "/") {
o.f.Get(o.Config().OpenAPIDocsPath+"/", func(c *fiber.Ctx) error {
return c.Redirect(o.Config().OpenAPIDocsPath)
})
}
}
// GetOperations returns all registered operations (useful for testing and documentation generation)
func (o *OApiApp) GetOperations() []OpenAPIOperation {
return o.operations
}
// GenerateOpenAPISpec generates a complete OpenAPI 3.0 specification
func (o *OApiApp) GenerateOpenAPISpec() map[string]interface{} {
spec := map[string]interface{}{
"openapi": "3.0.0",
"info": map[string]interface{}{
"title": "Fiber OpenAPI",
"version": "1.0.0",
"description": "API documentation generated by fiber-oapi",
},
"paths": make(map[string]interface{}),
"components": make(map[string]interface{}),
}
paths := spec["paths"].(map[string]interface{})
components := spec["components"].(map[string]interface{})
schemas := make(map[string]interface{})
components["schemas"] = schemas
// Add security schemes if configured
if len(o.config.SecuritySchemes) > 0 {
components["securitySchemes"] = o.config.SecuritySchemes
}
// Add default security if configured
if len(o.config.DefaultSecurity) > 0 {
spec["security"] = o.config.DefaultSecurity
}
// First pass: collect all types that need schemas
allTypes := make(map[string]reflect.Type)
for _, op := range o.operations {
if op.InputType != nil {
collectAllTypes(op.InputType, allTypes)
}
if op.OutputType != nil {
collectAllTypes(op.OutputType, allTypes)
}
if op.ErrorType != nil && !isEmptyStruct(op.ErrorType) {
collectAllTypes(op.ErrorType, allTypes)
}
}
// Second pass: generate all schemas
for typeName, typeInfo := range allTypes {
schemas[typeName] = generateSchema(typeInfo)
}
for _, op := range o.operations {
// Convert Fiber path format (:param) to OpenAPI format ({param})
openAPIPath := convertFiberPathToOpenAPI(op.Path)
if paths[openAPIPath] == nil {
paths[openAPIPath] = make(map[string]interface{})
}
pathItem := paths[openAPIPath].(map[string]interface{})
// Copy the options and enhance them with auto-generated schemas
enhancedOptions := make(map[string]interface{})
// Copy existing options
if op.Options.OperationID != "" {
enhancedOptions["operationId"] = op.Options.OperationID
}
if op.Options.Summary != "" {
enhancedOptions["summary"] = op.Options.Summary
}
if op.Options.Description != "" {
enhancedOptions["description"] = op.Options.Description
}
if len(op.Options.Tags) > 0 {
enhancedOptions["tags"] = op.Options.Tags
}
// Auto-generate parameters from struct tags and merge with manual parameters
autoParameters := []map[string]interface{}{}
if op.InputType != nil {
autoParameters = extractParametersFromStruct(op.InputType)
}
// Merge auto-generated parameters with manually defined ones
allParameters := autoParameters
if len(op.Options.Parameters) > 0 {
allParameters = mergeParameters(autoParameters, op.Options.Parameters)
}
if len(allParameters) > 0 {
enhancedOptions["parameters"] = allParameters
}
// Add security information
if op.Options.Security != nil {
if securityValue, ok := op.Options.Security.(string); ok && securityValue == "disabled" {
// Explicitly set empty security to override defaults
enhancedOptions["security"] = []map[string][]string{}
} else if securitySlice, ok := op.Options.Security.([]map[string][]string); ok {
enhancedOptions["security"] = securitySlice
}
}
// Add descriptions for required permissions
if len(op.Options.RequiredPermissions) > 0 {
desc := ""
if op.Options.Description != "" {
desc = op.Options.Description
}
desc += fmt.Sprintf("\n\n**Required Permissions:** %s", strings.Join(op.Options.RequiredPermissions, ", "))
enhancedOptions["description"] = desc
}
// Add request body schema for POST/PUT methods
if op.Method == "POST" || op.Method == "PUT" || op.Method == "PATCH" {
if op.InputType != nil {
inputType := dereferenceType(op.InputType)
var schemaRef map[string]interface{}
// For map types, use inline schema instead of reference
if inputType.Kind() == reflect.Map {
schemaRef = generateSchema(inputType)
} else {
inputSchemaName := getTypeName(inputType)
schemaRef = map[string]interface{}{
"$ref": "#/components/schemas/" + inputSchemaName,
}
}
enhancedOptions["requestBody"] = map[string]interface{}{
"required": true,
"content": map[string]interface{}{
"application/json": map[string]interface{}{
"schema": schemaRef,
},
},
}
}
}
// Add response schemas
responses := make(map[string]interface{})
// Success response (200)
if op.OutputType != nil {
outputType := dereferenceType(op.OutputType)
var schemaRef map[string]interface{}
// For map types, use inline schema instead of reference
if outputType.Kind() == reflect.Map {
schemaRef = generateSchema(outputType)
} else {
outputSchemaName := getTypeName(outputType)
schemaRef = map[string]interface{}{
"$ref": "#/components/schemas/" + outputSchemaName,
}
}
responses["200"] = map[string]interface{}{
"description": "Successful response",
"content": map[string]interface{}{
"application/json": map[string]interface{}{
"schema": schemaRef,
},
},
}
}
// Error response (400/500)
if op.ErrorType != nil && !isEmptyStruct(op.ErrorType) {
errorSchemaName := getTypeName(op.ErrorType)
responses["400"] = map[string]interface{}{
"description": "Validation error",
"content": map[string]interface{}{
"application/json": map[string]interface{}{
"schema": map[string]interface{}{
"$ref": "#/components/schemas/" + errorSchemaName,
},
},
},
}
}
enhancedOptions["responses"] = responses
pathItem[strings.ToLower(op.Method)] = enhancedOptions
}
return spec
}
// GenerateOpenAPISpecYAML generates the OpenAPI spec in YAML format
func (o *OApiApp) GenerateOpenAPISpecYAML() (string, error) {
spec := o.GenerateOpenAPISpec()
yamlData, err := yaml.Marshal(spec)
if err != nil {
return "", err
}
return string(yamlData), nil
}
// collectAllTypes recursively collects all types referenced by a given type
func collectAllTypes(t reflect.Type, collected map[string]reflect.Type) {
if t == nil {
return
}
// Handle pointers
t = dereferenceType(t)
typeName := getTypeName(t)
if typeName == "" {
return
}
// Skip if already processed
if _, exists := collected[typeName]; exists {
return
}
// Handle different kinds of types
switch t.Kind() {
case reflect.Struct:
// Only add structs that have a meaningful name
if typeName != "EmptyObject" && typeName != "AnonymousStruct" {
collected[typeName] = t
}
// Recursively collect types from all fields
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if !field.IsExported() {
continue
}
// Skip fields with json:"-" tag
if jsonTag := field.Tag.Get("json"); jsonTag == "-" {
continue
}
collectAllTypes(field.Type, collected)
}
case reflect.Map:
// Don't add map types as separate schemas - they're always inlined
// Just collect key and value types recursively
keyType := t.Key()
valueType := t.Elem()
collectAllTypes(keyType, collected)
collectAllTypes(valueType, collected)
case reflect.Slice:
// Add slice type for complex slices
if shouldGenerateSchemaForType(t) {
collected[typeName] = t
}
// Collect element type
collectAllTypes(t.Elem(), collected)
case reflect.Interface:
// For interface{}, we might want to document it
if t.NumMethod() == 0 && shouldGenerateSchemaForType(t) {
collected[typeName] = t
}
default:
// For basic types, we usually don't need separate schemas
// but if they have a name, they might be custom types
if t.Name() != "" && shouldGenerateSchemaForType(t) {
collected[typeName] = t
}
}
}
// shouldGenerateSchemaForType determines if a type should get its own schema
func shouldGenerateSchemaForType(t reflect.Type) bool {
if t == nil {
return false
}
// Handle pointers
t = dereferenceType(t)
switch t.Kind() {
case reflect.Struct:
// Always generate schema for structs (except empty ones)
return t.NumField() > 0
case reflect.Map:
// Generate schema for maps with complex value types
valueType := dereferenceType(t.Elem())
return valueType.Kind() == reflect.Struct ||
valueType.Kind() == reflect.Map ||
valueType.Kind() == reflect.Slice
case reflect.Slice:
// Generate schema for slices of complex types
elemType := dereferenceType(t.Elem())
return elemType.Kind() == reflect.Struct ||
elemType.Kind() == reflect.Map
case reflect.Interface:
// Generate schema for interface{} to document it properly
return t.NumMethod() == 0
default:
// For basic types, only if they're named custom types
return t.Name() != "" && t.PkgPath() != ""
}
}
// convertFiberPathToOpenAPI converts Fiber path format to OpenAPI format
// Example: /users/:id/posts/:postId -> /users/{id}/posts/{postId}
func convertFiberPathToOpenAPI(fiberPath string) string {
// Replace :param with {param}
parts := strings.Split(fiberPath, "/")
for i, part := range parts {
if strings.HasPrefix(part, ":") {
parts[i] = "{" + part[1:] + "}"
}
}
return strings.Join(parts, "/")
}
// getTypeName returns the name of a Go type for use in OpenAPI schema names
func getTypeName(t reflect.Type) string {
if t == nil {
return "EmptyObject"
}
// Handle pointers
t = dereferenceType(t)
// Handle different kinds of types
switch t.Kind() {
case reflect.Map:
// For maps, create a descriptive name
keyType := t.Key()
valueType := t.Elem()
return fmt.Sprintf("Map_%s_%s",
getSimpleTypeName(keyType),
getSimpleTypeName(valueType))
case reflect.Slice:
// For slices, create a descriptive name
elemType := t.Elem()
return fmt.Sprintf("Array_%s", getSimpleTypeName(elemType))
case reflect.Interface:
// For interfaces, use a generic name
if t.NumMethod() == 0 {
return "AnyValue" // interface{}
}
return "Interface"
default:
name := t.Name()
if name == "" {
// For anonymous structs, use the package path + "AnonymousStruct"
if t.Kind() == reflect.Struct {
return "AnonymousStruct"
}
return getSimpleTypeName(t)
}
return name
}
}
// getSimpleTypeName returns a simple name for basic types
func getSimpleTypeName(t reflect.Type) string {
if t == nil {
return "Any"
}
// Handle pointers
t = dereferenceType(t)
switch t.Kind() {
case reflect.String:
return "String"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return "Integer"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "UInteger"
case reflect.Float32, reflect.Float64:
return "Number"
case reflect.Bool:
return "Boolean"
case reflect.Interface:
return "Any"
case reflect.Map:
return "Object"
case reflect.Slice:
return "Array"
case reflect.Struct:
if name := t.Name(); name != "" {
return name
}
return "Object"
default:
return "Any"
}
}
// generateSchema generates an OpenAPI schema from a Go type
func generateSchema(t reflect.Type) map[string]interface{} {
if t == nil {
return map[string]interface{}{
"type": "object",
}
}
// Handle pointers
t = dereferenceType(t)
schema := make(map[string]interface{})
switch t.Kind() {
case reflect.Struct:
schema["type"] = "object"
properties := make(map[string]interface{})
required := []string{}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if !field.IsExported() {
continue
}
// Get JSON tag name
jsonTag := field.Tag.Get("json")
if jsonTag == "-" {
continue
}
fieldName := field.Name
if jsonTag != "" {
parts := strings.Split(jsonTag, ",")
if parts[0] != "" {
fieldName = parts[0]
}
}
// Generate field schema
fieldSchema := generateFieldSchema(field.Type)
// Add validation info from tags
if validateTag := field.Tag.Get("validate"); validateTag != "" {
addValidationToSchema(fieldSchema, validateTag)
// Check if field is required
if strings.Contains(validateTag, "required") {
required = append(required, fieldName)
}
}
// Add description from path/query tags
if pathTag := field.Tag.Get("path"); pathTag != "" {
fieldSchema["description"] = "Path parameter: " + pathTag
} else if queryTag := field.Tag.Get("query"); queryTag != "" {
fieldSchema["description"] = "Query parameter: " + queryTag
}
properties[fieldName] = fieldSchema
}
schema["properties"] = properties
if len(required) > 0 {
schema["required"] = required
}
case reflect.Map:
// Handle map types (like map[string]string, map[string]interface{}) - use inline schemas
schema["type"] = "object"
keyType := t.Key()
valueType := t.Elem()
// For string keys, we can use additionalProperties
if keyType.Kind() == reflect.String {
if valueType.Kind() == reflect.Interface && valueType.NumMethod() == 0 {
// For interface{}, allow any type
schema["additionalProperties"] = true
schema["example"] = map[string]interface{}{
"string_key": "string_value",
"number_key": 42,
"boolean_key": true,
}
} else {
schema["additionalProperties"] = generateFieldSchema(valueType)
// Add example for common map types
if valueType.Kind() == reflect.String {
schema["example"] = map[string]string{
"key1": "value1",
"key2": "value2",
}
}
}
} else {
// For non-string keys, treat as generic object
schema["additionalProperties"] = true
}
case reflect.Interface:
// Handle interface{} types - treat as any value
schema["description"] = "Any value (interface{})"
// Don't specify type to allow any JSON value
case reflect.String:
schema["type"] = "string"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
schema["type"] = "integer"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
schema["type"] = "integer"
schema["minimum"] = 0
case reflect.Float32, reflect.Float64:
schema["type"] = "number"
case reflect.Bool:
schema["type"] = "boolean"
case reflect.Slice:
schema["type"] = "array"
schema["items"] = generateFieldSchema(t.Elem())
default:
// Fallback for unknown types
schema["type"] = "object"
schema["description"] = fmt.Sprintf("Unknown type: %s", t.Kind().String())
}
return schema
}
// generateFieldSchema generates schema for a struct field
func generateFieldSchema(t reflect.Type) map[string]interface{} {
schema := make(map[string]interface{})
// Handle pointers
t = dereferenceType(t)
switch t.Kind() {
case reflect.String:
schema["type"] = "string"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
schema["type"] = "integer"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
schema["type"] = "integer"
schema["minimum"] = 0
case reflect.Float32, reflect.Float64:
schema["type"] = "number"
case reflect.Bool:
schema["type"] = "boolean"
case reflect.Slice:
schema["type"] = "array"
schema["items"] = generateFieldSchema(t.Elem())
case reflect.Map:
// Handle map types in fields - always use inline schemas to avoid reference issues
schema["type"] = "object"
keyType := t.Key()
valueType := t.Elem()
// For string keys, we can use additionalProperties
if keyType.Kind() == reflect.String {
if valueType.Kind() == reflect.Interface && valueType.NumMethod() == 0 {
// For interface{}, allow any type
schema["additionalProperties"] = true
schema["example"] = map[string]interface{}{
"string_key": "string_value",
"number_key": 42,
"boolean_key": true,
}
} else {
schema["additionalProperties"] = generateFieldSchema(valueType)
// Add example for common map types
if valueType.Kind() == reflect.String {
schema["example"] = map[string]string{
"key": "value",
}
}
}
} else {
// For non-string keys, treat as generic object
schema["additionalProperties"] = true
}
case reflect.Interface:
// Handle interface{} types
schema["description"] = "Any value (interface{})"
// Don't specify type to allow any JSON value
case reflect.Struct:
// For nested structs, reference the type name
typeName := getTypeName(t)
if typeName == "" || typeName == "EmptyObject" {
// For anonymous or empty structs, inline as object
schema["type"] = "object"
} else {
schema["$ref"] = "#/components/schemas/" + typeName
}
default:
// Fallback for unknown types
schema["type"] = "object"
schema["description"] = fmt.Sprintf("Unsupported type: %s", t.Kind().String())
}
return schema
}
// addValidationToSchema adds validation constraints to schema based on validate tags
func addValidationToSchema(schema map[string]interface{}, validateTag string) {
rules := strings.Split(validateTag, ",")
for _, rule := range rules {
rule = strings.TrimSpace(rule)
if rule == "required" {
// Required is handled at the object level
continue
} else if strings.HasPrefix(rule, "min=") {
if val := strings.TrimPrefix(rule, "min="); val != "" {
if schema["type"] == "string" {
schema["minLength"] = parseIntOrZero(val)
} else if schema["type"] == "integer" || schema["type"] == "number" {
schema["minimum"] = parseIntOrZero(val)
}
}
} else if strings.HasPrefix(rule, "max=") {
if val := strings.TrimPrefix(rule, "max="); val != "" {
if schema["type"] == "string" {
schema["maxLength"] = parseIntOrZero(val)
} else if schema["type"] == "integer" || schema["type"] == "number" {
schema["maximum"] = parseIntOrZero(val)
}
}
} else if rule == "email" {
schema["format"] = "email"
} else if rule == "uuid4" {
schema["format"] = "uuid"
} else if rule == "url" {
schema["format"] = "uri"
} else if strings.HasPrefix(rule, "oneof=") {
if val := strings.TrimPrefix(rule, "oneof="); val != "" {
values := strings.Split(val, " ")
schema["enum"] = values
}
}
}
}
// parseIntOrZero parses a string to int, returns 0 if parsing fails
func parseIntOrZero(s string) int {
if val, err := strconv.Atoi(s); err == nil {
return val
}
return 0
}
// isEmptyStruct checks if a type represents an empty struct
func isEmptyStruct(t reflect.Type) bool {
if t == nil {
return true
}
t = dereferenceType(t)
return t.Kind() == reflect.Struct && t.NumField() == 0
}
// Method defines a generic method for registering HTTP operations with OpenAPI documentation
func Method[TInput any, TOutput any, TError any](
router OApiRouter, // Interface instead of *OApiApp
m string,
path string,
handler HandlerFunc[TInput, TOutput, TError],
options OpenAPIOptions,
) {
app := router.GetApp()
fullPath := router.GetPrefix() + path
// Validate path parameters with the input struct
if err := validatePathParams[TInput](fullPath); err != nil {
panic(fmt.Sprintf("Path validation failed for %s: %v", fullPath, err))
}
// Register the operation for OpenAPI documentation with type information
var inputZero TInput
var outputZero TOutput
var errorZero TError
app.operations = append(app.operations, OpenAPIOperation{
Method: m,
Path: fullPath,
Options: options,
InputType: reflect.TypeOf(inputZero),
OutputType: reflect.TypeOf(outputZero),
ErrorType: reflect.TypeOf(errorZero),
})
// Wrapper
fiberHandler := func(c *fiber.Ctx) error {
input, err := parseInput[TInput](app, c, fullPath, &options)
if err != nil {
// Use custom validation error handler if configured
if app.config.ValidationErrorHandler != nil {
return app.config.ValidationErrorHandler(c, err)
}
// Default validation error response
return c.Status(400).JSON(ErrorResponse{
Code: 400,
Details: err.Error(),
Type: "validation_error",
})
}
output, customErr := handler(c, input)
if !isZero(customErr) {
return handleCustomError(c, customErr)
}
if err := c.JSON(output); err != nil {
if fallbackErr := c.Status(500).JSON(ErrorResponse{
Code: 500,
Details: "Failed to serialize response",
Type: "serialization_error",
}); fallbackErr != nil {
// Both serializations failed, return original error to Fiber
return err
}
return nil
}
return nil
}
app.f.Add(m, fullPath, fiberHandler)
}
// Get defines a GET operation for the OpenAPI documentation
func Get[TInput any, TOutput any, TError any](
router OApiRouter, // Now accepts both *OApiApp and *OApiGroup
path string,
handler HandlerFunc[TInput, TOutput, TError],
options OpenAPIOptions,
) {
Method(router, http.MethodGet, path, handler, options)
}
// Post defines a POST operation for the OpenAPI documentation
func Post[TInput any, TOutput any, TError any](
router OApiRouter, // Now accepts both *OApiApp and *OApiGroup
path string,
handler HandlerFunc[TInput, TOutput, TError],
options OpenAPIOptions,
) {
Method(router, http.MethodPost, path, handler, options)
}
// Put defines a PUT operation for the OpenAPI documentation
func Put[TInput any, TOutput any, TError any](
router OApiRouter, // Now accepts both *OApiApp and *OApiGroup
path string,
handler HandlerFunc[TInput, TOutput, TError],
options OpenAPIOptions,
) {
Method(router, http.MethodPut, path, handler, options)
}
// Delete defines a DELETE operation for the OpenAPI documentation
func Delete[TInput any, TOutput any, TError any](
router OApiRouter, // Now accepts both *OApiApp and *OApiGroup
path string,
handler HandlerFunc[TInput, TOutput, TError],
options OpenAPIOptions,
) {
Method(router, http.MethodDelete, path, handler, options)
}
// Head defines a HEAD operation for the OpenAPI documentation
func Head[TInput any, TOutput any, TError any](
router OApiRouter, // Now accepts both *OApiApp and *OApiGroup
path string,
handler HandlerFunc[TInput, TOutput, TError],
options OpenAPIOptions,
) {
Method(router, http.MethodHead, path, handler, options)
}
// Patch defines a PATCH operation for the OpenAPI documentation
func Patch[TInput any, TOutput any, TError any](
router OApiRouter, // Now accepts both *OApiApp and *OApiGroup
path string,
handler HandlerFunc[TInput, TOutput, TError],
options OpenAPIOptions,
) {
Method(router, http.MethodPatch, path, handler, options)
}