swaggerui

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package swaggerui provides Swagger UI serving and integration with the go-router and openapi packages.

Quick Start

import (
	"net/http"

	"github.com/joakimcarlsson/go-router/openapi"
	"github.com/joakimcarlsson/go-router/router"
	"github.com/joakimcarlsson/go-router/swaggerui"
)

func main() {
	r := router.New()

	// Create OpenAPI generator
	generator := openapi.NewGenerator(openapi.Info{
		Title:       "My API",
		Version:     "1.0.0",
		Description: "API documentation",
	})

	// Add your routes with documentation
	r.GET("/users", listUsers,
		openapi.WithSummary("List users"),
		openapi.WithJSONResponse[[]User](200, "List of users"),
	)

	// Setup Swagger UI
	setup := swaggerui.NewSetup(r, generator)
	setup.RegisterRoutes(r, "/openapi.json", "/docs")

	http.ListenAndServe(":8080", r)
}

UI Configuration

Customize the Swagger UI appearance and behavior:

config := swaggerui.DefaultUIConfig()
config.Title = "My API Documentation"
config.DarkMode = true
config.TryItOutEnabled = true
config.DocExpansion = "list"  // "list", "full", or "none"
config.DefaultModelRendering = "example"  // "example" or "model"

setup := swaggerui.NewSetup(r, generator)
setup.WithUIConfig(config)
setup.RegisterRoutes(r, "/openapi.json", "/docs")

Configuration Options

UIConfig provides the following options:

Title                    string  // Page title
SpecURL                  string  // URL to OpenAPI spec (set automatically)
SwaggerVersion           string  // Swagger UI version from CDN
DarkMode                 bool    // Enable dark theme
PersistAuthorization     bool    // Remember auth between sessions
DefaultModelsExpandDepth int     // Model expansion depth
DeepLinking              bool    // Enable deep linking
DocExpansion             string  // Default expansion: "list", "full", "none"
Filter                   bool    // Enable filtering
DisplayRequestDuration   bool    // Show request timing
TryItOutEnabled          bool    // Enable "Try it out" by default
RequestSnippetsEnabled   bool    // Show request snippets
DefaultModelRendering    string  // "example" or "model"
CustomCSS                string  // Additional CSS
CustomJS                 string  // Additional JavaScript

OAuth2 Configuration

Configure OAuth2 for the Swagger UI:

config := swaggerui.DefaultUIConfig()
config.OAuth2Config = &swaggerui.OAuth2Config{
	ClientID:     "your-client-id",
	ClientSecret: "your-client-secret",  // Optional
	AppName:      "My App",
	Scopes:       []string{"read", "write"},
	UsePkceWithAuthorizationCodeGrant: true,
}

setup := swaggerui.NewSetup(r, generator)
setup.WithUIConfig(config)
setup.RegisterRoutes(r, "/openapi.json", "/docs")

Standalone Handlers

Use the handlers directly without the Setup helper:

// Serve Swagger UI at a custom path
http.Handle("/swagger/", http.StripPrefix("/swagger",
	http.HandlerFunc(swaggerui.Handler(swaggerui.DefaultUIConfig()))))

// OAuth2 redirect handler
http.HandleFunc("/oauth2-redirect.html", swaggerui.OAuth2RedirectHandler())

Security Schemes

The Swagger UI automatically picks up security schemes defined in the OpenAPI generator:

generator := openapi.NewGenerator(openapi.Info{
	Title:   "Secure API",
	Version: "1.0.0",
})

// Add security schemes
generator.WithBearerAuth("bearerAuth", "JWT token")
generator.WithOAuth2AuthorizationCodeFlow(
	"oauth2",
	"OAuth2 authentication",
	"https://auth.example.com/authorize",
	"https://auth.example.com/token",
	map[string]string{
		"read":  "Read access",
		"write": "Write access",
	},
)

// Routes using security
r.GET("/protected", handler,
	openapi.WithBearerAuth(),
)

For route documentation, see the openapi package. For core routing, see the router package.

For more information: https://github.com/JoakimCarlsson/go-router

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handler

func Handler(config UIConfig) http.HandlerFunc

Handler returns an http.HandlerFunc that serves the Swagger UI. It generates an HTML page with Swagger UI configured based on the provided options.

func OAuth2RedirectHandler

func OAuth2RedirectHandler() http.HandlerFunc

OAuth2RedirectHandler returns an http.HandlerFunc that serves the OAuth2 redirect page. This page handles the OAuth2 callback and passes the authorization code back to Swagger UI.

Types

type OAuth2Config

type OAuth2Config struct {
	// ClientID is the OAuth2 client ID
	ClientID string
	// ClientSecret is the OAuth2 client secret (optional, not recommended for public clients)
	ClientSecret string
	// Realm is the OAuth2 realm
	Realm string
	// AppName is the application name displayed in the authorization dialog
	AppName string
	// ScopeSeparator is the separator for scopes
	ScopeSeparator string
	// Scopes are the default scopes to request
	Scopes string
	// AdditionalQueryParams are additional query parameters to include in the authorization request
	AdditionalQueryParams map[string]string
	// UsePkceWithAuthorizationCodeGrant enables PKCE for authorization code grant
	UsePkceWithAuthorizationCodeGrant bool
	// UseBasicAuthenticationWithAccessCodeGrant uses basic auth for access code grant
	UseBasicAuthenticationWithAccessCodeGrant bool
	// OAuth2RedirectUrl is the redirect URL for OAuth2
	OAuth2RedirectUrl string
}

OAuth2Config holds OAuth2 configuration for Swagger UI.

type Setup

type Setup struct {
	// contains filtered or unexported fields
}

Setup provides integration between the router, OpenAPI generator, and Swagger UI.

func NewSetup

func NewSetup(r *router.Router, generator *openapi.Generator) *Setup

NewSetup creates a new Swagger UI setup.

func (*Setup) RegisterRoutes

func (s *Setup) RegisterRoutes(r *router.Router, specPath, docsPath string)

RegisterRoutes registers the OpenAPI spec and Swagger UI routes.

func (*Setup) WithUIConfig

func (s *Setup) WithUIConfig(config UIConfig) *Setup

WithUIConfig sets the Swagger UI configuration.

type UIConfig

type UIConfig struct {
	// Title is the page title for the Swagger UI page
	Title string
	// SpecURL is the URL to the OpenAPI specification JSON
	SpecURL string
	// SwaggerVersion is the version of Swagger UI to use from the CDN
	SwaggerVersion string
	// DarkMode enables dark mode UI theme when true
	DarkMode bool
	// PersistAuthorization preserves the authorization data between browser sessions
	PersistAuthorization bool
	// DefaultModelsExpandDepth sets the default expansion depth for models
	DefaultModelsExpandDepth int
	// DeepLinking enables deeplinking for tags and operations
	DeepLinking bool
	// DocExpansion controls the default expansion setting for the operations
	// Allowed values are: "list" (expands only tags), "full" (expands everything), "none" (expands nothing)
	DocExpansion string
	// Filter enables filtering of operations
	Filter bool
	// AdditionalQueryParams allows adding query params to the OpenAPI spec URL
	AdditionalQueryParams map[string]string
	// DisplayRequestDuration shows how long API calls take
	DisplayRequestDuration bool
	// MaxDisplayedTags limits the number of tagged operations shown
	MaxDisplayedTags int
	// ShowExtensions displays vendor extensions
	ShowExtensions bool
	// TryItOutEnabled enables the "Try it out" feature by default
	TryItOutEnabled bool
	// RequestSnippetsEnabled enables the request snippets section
	RequestSnippetsEnabled bool
	// DefaultModelRendering controls how models are displayed
	// Possible values: "example" or "model"
	DefaultModelRendering string
	// CustomCSS allows injecting additional CSS styles
	CustomCSS string
	// CustomJS allows injecting custom JavaScript
	CustomJS string
	// OAuth2Config contains OAuth2 configuration for Swagger UI
	OAuth2Config *OAuth2Config
}

UIConfig holds configuration options for serving Swagger UI. It allows customization of the UI appearance, behavior, and features.

func DefaultUIConfig

func DefaultUIConfig() UIConfig

DefaultUIConfig returns a default configuration for Swagger UI. This provides sensible defaults for all UI options.

Jump to

Keyboard shortcuts

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