swagger

package
v1.5.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package swagger provides OpenAPI specification viewer middleware for celeris.

New returns a celeris.HandlerFunc that serves an interactive API reference page and the raw OpenAPI spec (JSON or YAML, auto-detected) under a configurable base path. By default it registers {BasePath}/ for the UI, {BasePath}/spec for the raw spec, and redirects {BasePath} to {BasePath}/; other paths and non-GET/HEAD methods pass through or return 405.

Config is the entry point. Provide the spec via Config.SpecContent (an embedded byte slice) or Config.SpecURL (an externally hosted spec, in which case no /spec endpoint is registered). Config.Renderer selects the frontend (RendererSwaggerUI (default), RendererScalar, or RendererReDoc), and Config.Options passes renderer-specific settings as a JSON-serializable map.

UIConfig (Config.UI) tunes the Swagger UI renderer — DocExpansion, Title, and OAuth2 pre-configuration via OAuth2Config; most of its fields are ignored by Scalar and ReDoc. Use IntPtr to set UIConfig.DefaultModelsExpandDepth, which is an *int so an explicit zero is distinguishable from unset. For air-gapped deployments, set Config.AssetsPath to serve bundled assets locally instead of from a CDN.

The middleware has no built-in authentication; OpenAPI specs may expose internal API structure, so place it after auth middleware to protect the endpoints.

//go:embed openapi.json
var spec []byte

server.Use(swagger.New(swagger.Config{SpecContent: spec}))

Documentation

Full guides and examples: https://goceleris.dev/docs/middleware-content

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IntPtr

func IntPtr(v int) *int

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,
	}))
}
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",
		},
	}))
}
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",
	}))
}
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",
	}))
}
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),
		},
	}))
}
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"},
			},
		},
	}))
}
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,
	}))
}
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,
		},
	}))
}
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,
	}))
}

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 (public; safe to embed).
	ClientID 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
	// UsePKCE enables Proof Key for Code Exchange (RFC 7636), the
	// recommended public-client flow. Default: true.
	UsePKCE bool
}

OAuth2Config pre-fills the OAuth2 authorization dialog in Swagger UI.

Browser flows MUST use PKCE — the public ClientID is the only secret material safe to embed in HTML. Confidential-client secrets cannot be kept secret in a browser; the previous ClientSecret field was removed in v1.3.4 because it shipped credentials in plaintext to every page load. If you have a server-side OAuth flow, perform the token exchange on your backend, not 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.
	// All values are embedded in the served HTML page source and visible
	// to anyone who can access the page; only public-client material is
	// supported (no ClientSecret — use PKCE via [OAuth2Config.UsePKCE]).
	// 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"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL