Repository navigation
feat(gen): embed OpenAPI document and serve it with Swagger UI - #1775
Merged
Merged
Conversation
Add a dependency-free runtime package that embeds swagger-ui-dist and serves the standalone layout: an index page rendered for a given spec URL and the static assets. Assets can alternatively be loaded from a CDN via Config.AssetsURL, in which case only the index page is served. The vendored files are updated with tools/swaggerui-update, exposed as `make update-swaggerui VERSION=<x.y.z>`. Only the files required by the standalone layout are copied; source maps and ES bundles are skipped. Serving Swagger UI from the same origin as the API avoids the CORS setup described in ogen-go#914. The package imports the standard library only, so generated servers do not pick up new third-party dependencies (ogen-go#1767). Refs ogen-go#914, ogen-go#1767
Add two opt-in features: - `server/spec` embeds the OpenAPI document into the generated package as JSON and YAML constants and generates SpecJSON, SpecYAML and SpecHandler, plus the WithDocs server option that serves `<prefix>/openapi.json` and `<prefix>/openapi.yaml` from the generated router. - `server/swagger_ui` (implies `server/spec`) additionally generates SwaggerUIHandler and serves Swagger UI at `<prefix>/` via WithDocs, using the new swaggerui package. Documentation paths are matched after the server path prefix is cut and before API routes, so parameterized routes cannot shadow them; unknown paths under the prefix still fall through to the API router and the NotFound handler. FindRoute and FindPath are not affected. By default the original document is embedded, preserving examples, descriptions and specification extensions. When external references were resolved, the expanded self-contained document produced by parser.Expand is embedded instead. The new `spec_source` option (`auto`, `raw`, `expanded`) overrides this behaviour. Mapping keys are converted to strings for JSON encoding, since OpenAPI documents commonly use integer response codes as YAML keys. Default features are unchanged, so existing generated code is not affected. This makes the spec export requested in ogen-go#878 and the embedding for Swagger UI requested in ogen-go#991 available out of the box. Refs ogen-go#878, ogen-go#991, ogen-go#914, ogen-go#1767
…update CodeQL flagged the archive extraction in tools/swaggerui-update as a potential "Zip Slip": the tar entry name was used to build the output path, and the allow-list check was not recognised as sanitisation. Only top-level entries under "package/" are considered now, and the destination file name is taken from the allow-list entry itself rather than from the archive entry, so archive content can never influence the written path.
The test FileSystem used in gen/gen_spec_test.go recorded written files in a plain map, but WriteSource writes files concurrently, which failed with "concurrent map writes" on macOS and under the race detector. Guard the map with a mutex. The swaggerui handler relied on the platform MIME database for asset content types, which maps ".js" to "application/javascript" on Windows. Set the Content-Type explicitly for the embedded asset extensions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR adds first-class support for serving the OpenAPI document and Swagger UI from a generated server, similar to https://petstore.swagger.io, without any manual
go:embedwiring.Two new opt-in generator features:
server/spec— embeds the OpenAPI document into the generated package (as JSON and YAML) and generatesSpecJSON(),SpecYAML(),SpecHandler()and theWithDocs(prefix, ...DocsOption)server option, which serves<prefix>/openapi.jsonand<prefix>/openapi.yamlfrom the generated router.server/swagger_ui(impliesserver/spec) — additionally generatesSwaggerUIHandler()and serves Swagger UI at<prefix>/viaWithDocs, withWithDocsTitleandWithDocsAssetsURLoptions.Standalone handlers can also be mounted into any router:
mux.Handle("/docs/", http.StripPrefix("/docs", api.SwaggerUIHandler())).Design notes
make generate examplesproduces no diff in existing generated packages.WithPathPrefixis respected) and before API routes, so parameterized routes like/{id}cannot shadow/docs. Only an exact set of paths is claimed; everything else under the prefix falls through to the API router and theNotFoundhandler.FindRoute/FindPathare not affected. Docs bypassMiddleware, which is per-operation.parser.Expandis embedded instead. The newgenerator.spec_sourceoption (auto|raw|expanded) overrides this. Mapping keys are converted to strings for JSON encoding, since OpenAPI documents commonly use integer response codes as YAML keys andyaml.Node.EncodeJSONrejects them.swaggerui. Embedsswagger-ui-dist5.33.2 (Apache-2.0,LICENSE/NOTICEincluded) and depends on the standard library only, so generated servers do not pick up third-party dependencies (see Runtime packages import openapi only for ParameterLocation, linking YAML, zap and color into generated servers #1767). Onlyserver/swagger_uiimports it;server/specalone adds no imports. Assets are updated withmake update-swaggerui VERSION=x.y.z(tools/swaggerui-update). Assets can be loaded from a CDN instead viaWithDocsAssetsURL.raw_stringtemplate helper), so committed generated code stays diff-friendly.Related issues
Refs #878, #991, #914, #1767
Testing
gen/gen_spec_test.go: generator unit tests (feature combinations, extensions preserved, integer keys, backticks in content, DSL-built specs withoutRaw, external references → expanded,spec_sourceoverride).swaggerui/swaggerui_test.go: handler tests (index, assets, 404/405, CDN mode).internal/integration/test_spec_docs+spec_docs_test.go: end-to-end tests throughhttptest(JSON/YAML, ETag/304, redirect, UI page, assets, customNotFound,WithPathPrefix, root mount, standalone mounting).go test ./...(root andexamples),golangci-lint runon touched packages,make generate examples+git diff --exit-codefor existing packages.Generated files are committed in a separate
chore: commit generated filescommit as described in CONTRIBUTING.md.