Skip to content

feat(gen): embed OpenAPI document and serve it with Swagger UI - #1775

Merged
ernado merged 5 commits into
ogen-go:mainfrom
ya-makariy:feat/serve-spec-swagger-ui
Oct 16, 2026
Merged

ernado merged 5 commits into
ogen-go:mainfrom
ya-makariy:feat/serve-spec-swagger-ui

Conversation

@ya-makariy

Copy link
Copy Markdown
Contributor

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:embed wiring.

Two new opt-in generator features:

  • server/spec — embeds the OpenAPI document into the generated package (as JSON and YAML) and generates SpecJSON(), SpecYAML(), SpecHandler() and the WithDocs(prefix, ...DocsOption) server option, which 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, with WithDocsTitle and WithDocsAssetsURL options.
generator:
  features:
    enable:
      - server/swagger_ui
srv, _ := api.NewServer(handler, api.WithDocs("/docs"))
http.ListenAndServe(":8080", srv) // http://localhost:8080/docs/

Standalone handlers can also be mounted into any router: mux.Handle("/docs/", http.StripPrefix("/docs", api.SwaggerUIHandler())).

Design notes

  • Default output is unchanged. Both features are off by default; make generate examples produces no diff in existing generated packages.
  • Routing. Documentation paths are matched after the server path prefix is cut (so WithPathPrefix is 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 the NotFound handler. FindRoute/FindPath are not affected. Docs bypass Middleware, which is per-operation.
  • Embedded document. By default the original document is embedded as parsed, so examples, descriptions and specification extensions are preserved. If external references were actually resolved (tracked by wrapping the external resolver), the self-contained document from parser.Expand is embedded instead. The new generator.spec_source option (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 and yaml.Node.EncodeJSON rejects them.
  • New runtime package swaggerui. Embeds swagger-ui-dist 5.33.2 (Apache-2.0, LICENSE/NOTICE included) 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). Only server/swagger_ui imports it; server/spec alone adds no imports. Assets are updated with make update-swaggerui VERSION=x.y.z (tools/swaggerui-update). Assets can be loaded from a CDN instead via WithDocsAssetsURL.
  • The spec constants are emitted as multi-line raw string literals (new raw_string template 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 without Raw, external references → expanded, spec_source override).
  • 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 through httptest (JSON/YAML, ETag/304, redirect, UI page, assets, custom NotFound, WithPathPrefix, root mount, standalone mounting).
  • go test ./... (root and examples), golangci-lint run on touched packages, make generate examples + git diff --exit-code for existing packages.
  • Manually verified with a Petstore demo server: Swagger UI renders and executes requests against the live API.

Generated files are committed in a separate chore: commit generated files commit as described in CONTRIBUTING.md.

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
Comment thread tools/swaggerui-update/main.go Fixed
…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.
@ernado
ernado merged commit d84283b into ogen-go:main Oct 16, 2026
15 checks passed
@ya-makariy
ya-makariy deleted the feat/serve-spec-swagger-ui branch October 16, 2026 07:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants