Documentation
¶
Overview ¶
Package swagger provides OpenAPI specification viewer middleware for celeris.
The middleware serves a Swagger UI (or Scalar / ReDoc) page and the raw OpenAPI spec at configurable URL paths. It supports both JSON and YAML specs with automatic content-type detection.
Basic usage with an embedded spec:
import "embed"
//go:embed openapi.json
var spec []byte
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
}))
Custom base path and UI options:
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
BasePath: "/docs",
UI: swagger.UIConfig{
DocExpansion: "full",
DeepLinking: true,
PersistAuthorization: true,
DefaultModelsExpandDepth: 1,
Title: "My API",
},
}))
Using Scalar instead of Swagger UI:
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
Renderer: swagger.RendererScalar,
}))
Using ReDoc instead of Swagger UI:
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
Renderer: swagger.RendererReDoc,
}))
Note that UIConfig options (DocExpansion, DeepLinking, PersistAuthorization, DefaultModelsExpandDepth) apply only to Swagger UI and are ignored when Renderer is Scalar or ReDoc.
Renderer-Specific Options ¶
Use Config.Options to pass renderer-specific configuration as a JSON-serializable map. For ReDoc these are passed to Redoc.init(), for Scalar they become the data-configuration attribute, and for Swagger UI they are passed to SwaggerUIBundle().
ReDoc dark theme example:
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
Renderer: swagger.RendererReDoc,
Options: map[string]any{
"theme": map[string]any{
"colors": map[string]any{"primary": map[string]any{"main": "#32329f"}},
},
"expandResponses": "200,201",
"hideDownloadButton": true,
},
}))
When Options is nil, each renderer uses its own defaults.
OAuth2 Pre-Configuration ¶
Swagger UI supports pre-filling the OAuth2 authorization dialog. Set UIConfig.OAuth2 to configure client credentials:
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
UI: swagger.UIConfig{
OAuth2RedirectURL: "https://example.com/oauth2-redirect",
OAuth2: &swagger.OAuth2Config{
ClientID: "my-client-id",
AppName: "My Application",
Scopes: []string{"read:api", "write:api"},
},
},
}))
WARNING: all OAuth2Config values including ClientSecret are embedded in the HTML page source and visible to anyone who can access the page. Only use ClientSecret for development or test environments. In production, use PKCE (public clients) which do not require a secret.
OAuth2 fields are ignored when Renderer is not RendererSwaggerUI.
External spec URL (no /spec endpoint registered):
server.Use(swagger.New(swagger.Config{
SpecURL: "https://petstore.swagger.io/v2/swagger.json",
}))
Air-Gapped / Self-Hosted Assets ¶
By default, CSS and JavaScript are loaded from public CDNs. For environments without internet access, set Config.AssetsPath to a local URL prefix and serve the bundled assets with a static file middleware:
server.Use(static.New(static.Config{
Root: "./swagger-ui-dist",
Prefix: "/swagger-assets",
}))
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
AssetsPath: "/swagger-assets",
}))
Content-Type Detection ¶
When serving the spec via the /spec endpoint, the middleware auto-detects whether the content is JSON or YAML. Detection checks the Config.SpecFile extension first (.json, .yaml, .yml), then inspects the first non-whitespace byte of the content ('{' or '[' indicates JSON; anything else is assumed YAML).
Endpoints ¶
The middleware registers:
- {BasePath}/ — renders the UI page (HTML)
- {BasePath}/spec — serves the raw spec (JSON or YAML)
- {BasePath} — redirects to {BasePath}/
Requests to other paths pass through. Only GET and HEAD are handled; other methods return 405.
Ordering ¶
The swagger middleware intercepts by path prefix and can be placed at any position in the celeris.Server.Use chain. Place it after authentication middleware if you want to protect the spec and UI endpoints.
Skipping ¶
Use Config.Skip for dynamic skip logic or Config.SkipPaths for exact-match path exclusions. Skipped requests call c.Next() without serving the UI or spec.
Security ¶
The middleware has no built-in authentication. OpenAPI specs may reveal internal API structure. Protect the endpoints with upstream auth middleware or network-level controls. When using CDN-loaded assets, ensure your CSP policy allows cdn.jsdelivr.net (Scalar) or unpkg.com (Swagger UI) in script-src and style-src.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IntPtr ¶
IntPtr returns a pointer to v. Use with UIConfig.DefaultModelsExpandDepth to distinguish explicit zero from unset:
swagger.IntPtr(0) // show model names only swagger.IntPtr(-1) // hide models section
func New ¶
func New(config ...Config) celeris.HandlerFunc
New creates a swagger middleware that serves an OpenAPI spec viewer.
Example ¶
package main
import (
"github.com/goceleris/celeris"
"github.com/goceleris/celeris/middleware/swagger"
)
func main() {
server := celeris.New(celeris.Config{})
spec := []byte(`{"openapi":"3.0.0","info":{"title":"Test","version":"1.0"}}`)
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
}))
}
Output:
Example (CustomUI) ¶
package main
import (
"github.com/goceleris/celeris"
"github.com/goceleris/celeris/middleware/swagger"
)
func main() {
server := celeris.New(celeris.Config{})
spec := []byte(`{"openapi":"3.0.0","info":{"title":"Test","version":"1.0"}}`)
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
BasePath: "/docs",
UI: swagger.UIConfig{
DocExpansion: "full",
DeepLinking: true,
PersistAuthorization: true,
Title: "My API",
},
}))
}
Output:
Example (ExternalSpec) ¶
package main
import (
"github.com/goceleris/celeris"
"github.com/goceleris/celeris/middleware/swagger"
)
func main() {
server := celeris.New(celeris.Config{})
server.Use(swagger.New(swagger.Config{
SpecURL: "https://petstore.swagger.io/v2/swagger.json",
}))
}
Output:
Example (LocalAssets) ¶
package main
import (
"github.com/goceleris/celeris"
"github.com/goceleris/celeris/middleware/swagger"
)
func main() {
server := celeris.New(celeris.Config{})
spec := []byte(`{"openapi":"3.0.0","info":{"title":"Test","version":"1.0"}}`)
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
AssetsPath: "/swagger-assets",
}))
}
Output:
Example (ModelsExpandDepth) ¶
package main
import (
"github.com/goceleris/celeris"
"github.com/goceleris/celeris/middleware/swagger"
)
func main() {
server := celeris.New(celeris.Config{})
spec := []byte(`{"openapi":"3.0.0","info":{"title":"Test","version":"1.0"}}`)
// Use IntPtr to set DefaultModelsExpandDepth to 0 (show model names only).
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
UI: swagger.UIConfig{
DefaultModelsExpandDepth: swagger.IntPtr(0),
},
}))
}
Output:
Example (Oauth2) ¶
package main
import (
"github.com/goceleris/celeris"
"github.com/goceleris/celeris/middleware/swagger"
)
func main() {
server := celeris.New(celeris.Config{})
spec := []byte(`{"openapi":"3.0.0","info":{"title":"Test","version":"1.0"}}`)
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
UI: swagger.UIConfig{
OAuth2RedirectURL: "https://example.com/oauth2-redirect",
OAuth2: &swagger.OAuth2Config{
ClientID: "my-client-id",
AppName: "My Application",
Scopes: []string{"read:api", "write:api"},
},
},
}))
}
Output:
Example (Redoc) ¶
package main
import (
"github.com/goceleris/celeris"
"github.com/goceleris/celeris/middleware/swagger"
)
func main() {
server := celeris.New(celeris.Config{})
spec := []byte(`{"openapi":"3.0.0","info":{"title":"Test","version":"1.0"}}`)
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
Renderer: swagger.RendererReDoc,
}))
}
Output:
Example (RedocCustom) ¶
package main
import (
"github.com/goceleris/celeris"
"github.com/goceleris/celeris/middleware/swagger"
)
func main() {
server := celeris.New(celeris.Config{})
spec := []byte(`{"openapi":"3.0.0","info":{"title":"Test","version":"1.0"}}`)
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
Renderer: swagger.RendererReDoc,
Options: map[string]any{
"theme": map[string]any{
"colors": map[string]any{"primary": map[string]any{"main": "#32329f"}},
},
"expandResponses": "200",
"hideDownloadButton": true,
},
}))
}
Output:
Example (Scalar) ¶
package main
import (
"github.com/goceleris/celeris"
"github.com/goceleris/celeris/middleware/swagger"
)
func main() {
server := celeris.New(celeris.Config{})
spec := []byte(`{"openapi":"3.0.0","info":{"title":"Test","version":"1.0"}}`)
server.Use(swagger.New(swagger.Config{
SpecContent: spec,
Renderer: swagger.RendererScalar,
}))
}
Output:
Types ¶
type Config ¶
type Config struct {
// Skip defines a function to skip this middleware for certain requests.
Skip func(c *celeris.Context) bool
// SkipPaths lists paths to skip (exact match on c.Path()).
SkipPaths []string
// BasePath is the URL prefix for the swagger endpoints.
// Default: "/swagger".
// The middleware registers:
// {BasePath}/ — UI page
// {BasePath}/spec — raw spec file
BasePath string
// SpecContent is the raw OpenAPI specification content (JSON or YAML).
// Either SpecContent or SpecURL must be set.
SpecContent []byte
// SpecURL is a URL to an externally hosted spec file. When set,
// SpecContent is ignored and no /spec endpoint is registered.
SpecURL string
// SpecFile is the original filename of the spec (e.g. "openapi.yaml").
// Used as a hint for content-type detection when SpecContent is provided.
// When omitted, content-type is detected from the spec bytes.
SpecFile string
// Renderer selects the UI renderer. Default: RendererSwaggerUI.
Renderer UIRenderer
// UI controls the appearance and behavior of the UI renderer.
UI UIConfig
// Options provides renderer-specific configuration as a JSON-serializable
// map. For Swagger UI, these are passed to SwaggerUIBundle(). For ReDoc,
// these are passed to Redoc.init(). For Scalar, these are passed as
// data-configuration. When nil, renderer defaults are used.
//
// Example (ReDoc dark theme):
//
// swagger.Config{
// SpecContent: spec,
// Renderer: swagger.RendererReDoc,
// Options: map[string]any{
// "theme": map[string]any{
// "colors": map[string]any{"primary": map[string]any{"main": "#32329f"}},
// },
// "expandResponses": "200,201",
// "hideDownloadButton": true,
// },
// }
Options map[string]any
// AssetsPath, when set, serves Swagger UI assets from a local path
// instead of the default CDN. The HTML template references scripts and
// stylesheets from this prefix (e.g. {AssetsPath}/swagger-ui-bundle.js).
//
// Users must serve the assets themselves, for example with a static
// file middleware:
//
// server.Use(static.New(static.Config{Root: "./swagger-ui-dist", Prefix: "/swagger-assets"}))
// server.Use(swagger.New(swagger.Config{
// SpecContent: spec,
// AssetsPath: "/swagger-assets",
// }))
AssetsPath string
}
Config defines the swagger middleware configuration.
type OAuth2Config ¶
type OAuth2Config struct {
// ClientID is the OAuth2 client identifier.
ClientID string
// ClientSecret is the OAuth2 client secret. Only for confidential clients.
ClientSecret string
// Realm is the OAuth2 realm.
Realm string
// AppName is the application name shown in the authorization dialog.
AppName string
// Scopes lists the default OAuth2 scopes to request.
Scopes []string
}
OAuth2Config pre-fills the OAuth2 authorization dialog in Swagger UI.
type UIConfig ¶
type UIConfig struct {
// DocExpansion controls how operations are displayed on first load.
// Valid values: "list" (default, expand tags), "full" (expand everything),
// "none" (collapse all).
// Swagger UI only; ignored when Renderer is Scalar or ReDoc.
DocExpansion string
// DeepLinking enables deep linking for tags and operations.
// Swagger UI only; ignored when Renderer is Scalar or ReDoc.
DeepLinking bool
// PersistAuthorization persists authorization data across browser sessions.
// Swagger UI only; ignored when Renderer is Scalar or ReDoc.
PersistAuthorization bool
// DefaultModelsExpandDepth controls how deep models are expanded.
// Default: nil (Swagger UI default, which is 1). Use [IntPtr] to set
// an explicit value: IntPtr(0) for model names only, IntPtr(-1) to
// hide the models section entirely.
// Swagger UI only; ignored when Renderer is Scalar or ReDoc.
DefaultModelsExpandDepth *int
// OAuth2RedirectURL sets the OAuth2 redirect URL for Swagger UI.
// Swagger UI only; ignored when Renderer is Scalar or ReDoc.
OAuth2RedirectURL string
// OAuth2 pre-fills the OAuth2 authorization dialog in Swagger UI.
// WARNING: all values including ClientSecret are embedded in the HTML
// page source and visible to anyone who can access the page. Only use
// ClientSecret for development or test environments. In production,
// use PKCE (public clients) which do not require a secret.
// When nil, no OAuth2 initialization is emitted.
// Swagger UI only; ignored when Renderer is Scalar or ReDoc.
OAuth2 *OAuth2Config
// Title is the HTML page title. Default: "API Documentation".
Title string
}
UIConfig controls the appearance and behavior of the Swagger UI or Scalar renderer.
type UIRenderer ¶
type UIRenderer string
UIRenderer selects the frontend used to render the API specification.
const ( // RendererSwaggerUI uses Swagger UI (default). RendererSwaggerUI UIRenderer = "swagger-ui" // RendererScalar uses Scalar API reference. RendererScalar UIRenderer = "scalar" // RendererReDoc uses ReDoc API reference. RendererReDoc UIRenderer = "redoc" )