go_swagger_ui

package module
v0.0.1-beta.3 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2024 License: Apache-2.0 Imports: 17 Imported by: 2

README

go-swagger-ui

go-swagger-ui provides a simple way to serve Swagger UI in your Go web application. It embeds Swagger UI and provides a customizable http.Handler to serve it.

Features

  • Provides a customizable HTTP Handler to serve Swagger UI.
  • Supports many of Swagger UI's configuration options.
  • Supports dynamic UI configuration in your Go application.
  • Provides a CLI application to open OpenAPI specification files in a Swagger UI instance (browser window).

Installation

To install the go-swagger-ui package, use the following command:

go get github.com/alexliesenfeld/go-swagger-ui

Usage

package main

import (
	"fmt"
	swaggerui "github.com/alexliesenfeld/go-swagger-ui"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/", swaggerui.NewHandler(
		swaggerui.WithHTMLTitle("My Example Petstore API"),
		swaggerui.WithSpecURL("https://petstore.swagger.io/v2/swagger.json"),
		swaggerui.WithTryItOutEnabled(true),
		swaggerui.WithPersistAuthorization(true),
	))

	fmt.Println("Starting server at port 8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

CLI Usage

Install the CLI application:

go install github.com/alexliesenfeld/go-swagger-ui/cmd/swui@latest

You can then use the CLI tool to serve OpenAPI spec files in a separate Swagger UI instance in a browser window.

swui /path/to/openapi-spec.yaml

swui also allows you to reload the browser window to see changes made to the spec file.

Roadmap

  • Embed Swagger UI
  • Provide simple but powerful http.Handler that is compatible with major web libraries
  • Allow to change the majority of configuration parameters from within a Go application
  • Make it possible to configure multiple spec file urls
  • Provide a CLI tool to view OpenAPI spec files locally in a browser
  • Add OAuth2 configuration possibilities (https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/oauth2.md)
  • Make plugins configurable
  • Make presets configurable
  • Allow using CDN instead of embedding Swagger UI

License

go-swagger-ui is free software: you can use it under the terms of the Apache License 2.0 license.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

This library includes Swagger UI as static resources. Swagger UI is a product of SmartBear Software Inc. and is made available under the Apache License 2.0. For complete details of the license, please refer to the official license text available at this link. It's important to note that as per the requirements of the Apache-2.0 license, this documentation serves as an attribution to SmartBear Software Inc., acknowledging their development of Swagger UI. Users of this library are advised to ensure they are in compliance with the Apache-2.0 license terms when utilizing Swagger UI as part of this library.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Must

func Must[T any](v T, err error) T

func NewHandler

func NewHandler(opts ...Option) http.HandlerFunc

Types

type DocExpansion

type DocExpansion string
var (
	DocExpansionList DocExpansion = "list"
	DocExpansionFull DocExpansion = "full"
	DocExpansionNone DocExpansion = "none"
)

type Layout

type Layout string
var (
	LayoutBaseLayout       Layout = "BaseLayout"
	LayoutStandaloneLayout Layout = "StandaloneLayout"
)
var (
	PresetAPIPreset Layout = "ApiPreset"
)

type ModelRendering

type ModelRendering string
var (
	ModelRenderingExample ModelRendering = "example"
	ModelRenderingModel   ModelRendering = "model"
)

type Option

type Option func(*uiConfig)

Option is a function that takes a pointer to uiConfig and modifies it.

func WithBasePath

func WithBasePath(basePath string) Option

WithBasePath sets the path prefix Swagger UI is provided on the server For example, if Swagger UI is provided under https://example.com/my-service/swagger-ui, the base path would be "/my-service/swagger-ui"). This will allow the handler to receive requests on path "my-service/swagger-ui" without a trailing slash (i.e., "/my-service/swagger-ui/"). Internally, the base path will be used to set a prefix for Swagger UI asset files (CSS, JavaScript, etc.).

func WithConfigURL

func WithConfigURL(configURL string) Option

WithConfigURL sets the URL to fetch external configuration document from.

func WithCredentials

func WithCredentials(withCredentials bool) Option

WithCredentials enables passing credentials, as defined in the Fetch standard, in CORS requests that are sent by the browser. Note that Swagger UI cannot currently set cookies cross-domain (see swagger-js#1163) - as a result, you will have to rely on browser-supplied cookies (which this setting enables sending) that Swagger UI cannot control.

func WithDeepLinking

func WithDeepLinking(deepLinking bool) Option

WithDeepLinking enables deep linking. See documentation at https://swagger.io/docs/open-source-tools/swagger-ui/usage/deep-linking/ for more information.

func WithDefaultModelExpandDepth

func WithDefaultModelExpandDepth(defaultModelExpandDepth int) Option

WithDefaultModelExpandDepth sets the default expansion depth for the model on the model-example section.

func WithDefaultModelRendering

func WithDefaultModelRendering(defaultModelRendering ModelRendering) Option

WithDefaultModelRendering controls how the model is shown when the API is first rendered. The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.

func WithDefaultModelsExpandDepth

func WithDefaultModelsExpandDepth(defaultModelsExpandDepth int) Option

WithDefaultModelsExpandDepth sets the default expansion depth for models (set to -1 completely hide the models).

func WithDisplayOperation

func WithDisplayOperation(displayOperationID bool) Option

WithDisplayOperation controls the display of operationId in operations list. The default is false.

func WithDisplayRequestDuration

func WithDisplayRequestDuration(displayRequestDuration bool) Option

WithDisplayRequestDuration controls the display of the request duration (in milliseconds) for "Try it out" requests.

func WithDocExpansion

func WithDocExpansion(value DocExpansion) Option

WithDocExpansion controls the default expansion setting for the operations and tags.

func WithFilter

func WithFilter(enabled bool, expression string) Option

WithFilter enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown. If enabled and a non-empty expression string is passed, then filtering will be enabled using that string as the filter expression. Filtering is case-sensitive matching the filter expression anywhere inside the tag. Leave the expression empty, if you only want to enable filtering but do not need a filter expression.

func WithHTMLTitle

func WithHTMLTitle(title string) Option

WithHTMLTitle sets the index HTML page htmlTitle.

func WithLayout

func WithLayout(layout Layout) Option

WithLayout sets the name of a component available via the plugin system to use as the top-level layout for Swagger UI. Possible values are "BaseLayout" and "StandaloneLayout". Default is "BaseLayout".

func WithMaxDisplayedTags

func WithMaxDisplayedTags(maxTags int) Option

WithMaxDisplayedTags limits the number of tagged operations displayed to at most this many. The default is to show all operations.

func WithOauth2RedirectUrl

func WithOauth2RedirectUrl(oauth2RedirectUrl string) Option

WithOauth2RedirectUrl sets the OAuth redirect URL.

func WithPersistAuthorization

func WithPersistAuthorization(persistAuthorization bool) Option

WithPersistAuthorization configures Swagger UI to persist authorization data, so that it is not lost on browser close/refresh.

func WithPresets

func WithPresets(preset Preset) Option

WithPresets sets the list of presets to use in Swagger UI. Usually, you'll want to include PresetAPIPreset if you use this option.

func WithQueryConfigEnabled

func WithQueryConfigEnabled(queryConfigEnabled bool) Option

WithQueryConfigEnabled enables overriding configuration parameters via URL search params.

func WithShowCommonExtensions

func WithShowCommonExtensions(showCommonExtensions bool) Option

WithShowCommonExtensions controls the display of extensions (pattern, maxLength, minLength, maximum, minimum) fields and values for Parameters.

func WithShowExtensions

func WithShowExtensions(showExtensions bool) Option

WithShowExtensions controls the display of vendor extension (x-) fields and values for Operations, Parameters, Responses, and Schema.

func WithShowMutatedRequest

func WithShowMutatedRequest(showMutatedRequest bool) Option

WithShowMutatedRequest configures Swagger UI to use the mutated request returned from a requestInterceptor to produce the curl command in the UI, otherwise the request before the requestInterceptor was applied is used. Refer to https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ for more information.

func WithSpec

func WithSpec(value []byte) Option

WithSpec sets an OpenAPI specification document content. When used, the URL configuration setting will not be used. This is useful for testing manually-generated definitions without hosting them.

func WithSpecFilePath

func WithSpecFilePath(path string) Option

WithSpecFilePath sets a file path to read from the OS file system. THIS OPTION IS NOT RECOMMENDED FOR PRODUCTION USE, because it reloads the file on every request. This option only exist to for testing purposes. Once file content is read, it will be used to set the spec field of https://github.com/swagger-api/swagger-ui/blob/HEAD/docs/usage/configuration.md and is equivalent to the WithSpec function.

func WithSpecURL

func WithSpecURL(value string) Option

WithSpecURL sets the URL pointing to API definition (normally swagger.json or swagger.yaml). Will be ignored if WithSpecURLs or WithSpec is used.

func WithSpecURLs

func WithSpecURLs(primary string, urls []SpecURL) Option

WithSpecURLs sets the URLs array to multiple API definitions that are used by Topbar plugin. When used and Topbar plugin is enabled, the settings from WithSpecURL will not be used. Names and URLs must be unique among all items in this array, since they're used as identifiers. If the value of the 'primary' parameter matches the name of a spec provided in urls, that spec will be displayed when Swagger UI loads, instead of defaulting to the first spec in urls. Leave parameter 'primary' empty, if you do not want to set a preselected URL.

func WithSupportedSubmitMethods

func WithSupportedSubmitMethods(supportedSubmitMethods ...string) Option

WithSupportedSubmitMethods sets a list of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display. Default is: ["get", "put", "post", "delete", "options", "head", "patch", "trace"].

func WithTryItOutEnabled

func WithTryItOutEnabled(tryItOutEnabled bool) Option

WithTryItOutEnabled controls whether the "Try it out" section should be enabled by default.

func WithValidatorURL

func WithValidatorURL(enabled bool, validatorUrl string) Option

WithValidatorURL sets the validator URL to use to validate specification files. By default, Swagger UI attempts to validate specs against swagger.io's online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators (e.g., Validator Badge, see https://github.com/swagger-api/validator-badge). Disabling it or setting the URL to 127.0.0.1 or localhost will disable validation.

type Preset

type Preset string

type SpecURL

type SpecURL struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

Directories

Path Synopsis
cmd
examples module

Jump to

Keyboard shortcuts

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