swagger

package module
v0.20.12 Latest Latest
Warning

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

Go to latest
Published: May 5, 2026 License: MIT Imports: 16 Imported by: 2

README

gswagger

This is a maintained fork of gswagger originally created by Davide Bianchi, now maintained by Lume Web.

Generate an OpenAPI spec dynamically based on the types used to handle request and response.

It works with any router, it is simple to add support to your router implementing the apirouter interface.

The routers supported out of the box are:

This lib uses [kin-openapi] to automatically generate and serve a swagger file.

To convert struct to schemas, we use [jsonschema] library.
The struct must contains the appropriate struct tags to be inserted in json schema to generate the schema dynamically.
It is always possible to add a totally custom swagger schema using [kin-openapi].

Install

To use it, install with

go get go.lumeweb.com/gswagger

Usage

An example usage of this lib with gorilla mux:

context := context.Background()
muxRouter := mux.NewRouter()

router, _ := swagger.NewRouter(gorilla.NewRouter(muxRouter), swagger.Options{
  Context: context,
  Openapi: &openapi3.T{
    Info: &openapi3.Info{
      Title:   "my title",
      Version: "1.0.0",
    },
  },
})

okHandler := func(w http.ResponseWriter, req *http.Request) {
  w.WriteHeader(http.StatusOK)
  w.Write([]byte("OK"))
}

type User struct {
  Name        string   `json:"name" jsonschema:"title=The user name,required" jsonschema_extras:"example=Jane"`
  PhoneNumber int      `json:"phone" jsonschema:"title=mobile number of user"`
  Groups      []string `json:"groups,omitempty" jsonschema:"title=groups of the user,default=users"`
  Address     string   `json:"address" jsonschema:"title=user address"`
}
type errorResponse struct {
  Message string `json:"message"`
}

router.AddRoute(http.MethodPost, "/users", okHandler, swagger.Definitions{
  RequestBody: &swagger.ContentValue{
    Content: swagger.Content{
      "application/json": {Value: User{}},
    },
  },
  Responses: map[int]swagger.ContentValue{
    201: {
      Content: swagger.Content{
        "text/html": {Value: ""},
      },
    },
    401: {
      Content: swagger.Content{
        "application/json": {Value: &errorResponse{}},
      },
      Description: "invalid request",
    },
  },
})

router.AddRoute(http.MethodGet, "/users", okHandler, swagger.Definitions{
  Responses: map[int]swagger.ContentValue{
    200: {
      Content: swagger.Content{
        "application/json": {Value: &[]User{}},
      },
    },
  },
})

carSchema := openapi3.NewObjectSchema().WithProperties(map[string]*openapi3.Schema{
  "foo": openapi3.NewStringSchema(),
  "bar": openapi3.NewIntegerSchema().WithMax(15).WithMin(5),
})
requestBody := openapi3.NewRequestBody().WithJSONSchema(carSchema)
operation := swagger.NewOperation()
operation.AddRequestBody(requestBody)

router.AddRawRoute(http.MethodPost, "/cars", okHandler, operation)

router.GenerateAndExposeOpenapi()

This configuration will output the schema shown here.

Auto generated path params schema

The path params, if not set in schema, are auto generated from the path. The format of the path parameters depends on the router library you are using, as explained below.

Gorilla Mux

Gorilla Mux supports the path parameters as {someParam}, for example as in /users/{userId}.

Here is the example test.

The generated oas schema will contains userId, carId and driverId as path params set to string. If only one params is set, you must specify manually all the path params.

The generated OAS for this test case is visible here.

Fiber

Fiber supports the path parameters as :someParam, for example as in /users/:userId.

Here is the example test

SubRouter

It is possible to create a new sub router from the swagger.Router. It is possible to add a prefix to all the routes created under the specific router (instead of use the router specific methods, if given, or repeat the prefix for every route).

It could also be useful if you need a sub router to create a group of APIs which use the same middleware (for example,this could be achieved by the SubRouter features of gorilla mux, for example).

To see the SubRouter example, please see the integration test of one of the supported routers.

FAQ
  1. How to add format binary? Formats date-time, email, hostname, ipv4, ipv6, uri could be added with tag jsonschema. Others format could be added with tag jsonschema_extra. Not all the formats are supported (see discovered unsupported formats here).

  2. How to add a swagger with allOf? You can create manually a swagger with allOf using the AddRawRoute method.

  3. How to add a swagger with anyOf? You can create manually a swagger with anyOf using the AddRawRoute method.

  4. How to add a swagger with oneOf? You can create manually a swagger with oneOf using the AddRawRoute method, or use the [jsonschema] struct tag.

Discovered unsupported schema features

Formats:

  • uuid is unsupported by [kin-openapi]

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Acknowledgements

This project is based on the excellent work of Davide Bianchi's gswagger. Lume Web maintains this fork with specific modifications while preserving all original functionality.

Documentation

Index

Constants

View Source
const (
	// DefaultJSONDocumentationPath is the path of the openapi documentation in json format.
	DefaultJSONDocumentationPath = "/documentation/json"
	// DefaultYAMLDocumentationPath is the path of the openapi documentation in yaml format.
	DefaultYAMLDocumentationPath = "/documentation/yaml"
)

Variables

View Source
var (
	ErrGenerateOAS       = errors.New("fail to generate openapi")
	ErrValidatingOAS     = errors.New("fails to validate openapi")
	ErrGenerateSwagger   = ErrGenerateOAS
	ErrValidatingSwagger = ErrValidatingOAS
)
View Source
var (
	// ErrResponses indicates failure generating response schemas
	ErrResponses = errors.New("errors generating responses schema")
	// ErrRequestBody indicates failure generating request body schema
	ErrRequestBody = errors.New("errors generating request body schema")
	// ErrPathParams indicates failure generating path parameter schemas
	ErrPathParams = errors.New("errors generating path parameters schema")
	// ErrQuerystring indicates failure generating querystring parameter schemas
	ErrQuerystring = errors.New("errors generating querystring schema")
)

Error variables for OpenAPI schema generation failures

Functions

func GetRouter

func GetRouter[T any, H any, M any, R any](r apirouter.Router[H, M, R]) T

func ResolveAllComponents added in v0.18.1

func ResolveAllComponents(rootSchema *openapi3.T) error

ResolveAllComponents processes all reusable components to resolve their references

Types

type Content

type Content map[string]Schema

Content defines media type schemas for request/response bodies Key is media type (e.g. "application/json"), value is Schema

type ContentValue

type ContentValue struct {
	Content     Content           // Media type schemas
	Description string            // Human-readable description
	Headers     map[string]string // Response headers
	Required    bool              // Whether body is required
}

ContentValue defines request/response body content

type Definitions

type Definitions struct {
	Extensions  map[string]any                 // OpenAPI extensions
	Tags        []string                       // Logical grouping tags
	Summary     string                         // Short summary
	Description string                         // Detailed description
	Deprecated  bool                           // Whether endpoint is deprecated
	Parameters  map[string]ParameterDefinition // Reusable parameters
	PathParams  ParameterValue                 // Path parameters
	Querystring ParameterValue                 // Query parameters
	Headers     ParameterValue                 // Header parameters
	Cookies     ParameterValue                 // Cookie parameters
	RequestBody *ContentValue                  // Request body definition
	Responses   map[int]ContentValue           // Response definitions by status code
	Security    SecurityRequirements           // Security requirements
}

Definitions provides OpenAPI schema definitions for a route

type Operation

type Operation struct {
	*openapi3.Operation
}

Operation wraps an OpenAPI 3.0 operation with additional helper methods. It provides a more convenient interface for building OpenAPI operations while maintaining compatibility with the underlying openapi3.Operation.

func NewOperation

func NewOperation() Operation

NewOperation creates and returns a new Operation instance. Initializes the underlying openapi3.Operation with: - Empty responses map - Nil request body - Nil security requirements NewOperation creates and returns a new Operation instance. Initializes the underlying openapi3.Operation with: - Empty responses map - Nil request body - Nil security requirements

func (*Operation) AddRequestBody

func (o *Operation) AddRequestBody(requestBody *openapi3.RequestBody)

AddRequestBody sets the request body definition for the operation. The requestBody parameter should be a fully configured openapi3.RequestBody containing the expected content types and schemas. AddRequestBody sets the request body definition for the operation. The requestBody parameter should be a fully configured openapi3.RequestBody containing the expected content types and schemas.

func (*Operation) AddResponse

func (o *Operation) AddResponse(status int, response *openapi3.Response)

AddResponse adds a response definition to the operation. Ensures responses map is initialized and sets empty description if none provided. Parameters:

  • status: HTTP status code (e.g. 200, 404)
  • response: OpenAPI response definition containing:
  • Description
  • Content types and schemas
  • Headers

AddResponse adds a response definition to the operation. Ensures responses map is initialized and sets empty description if none provided. Parameters:

  • status: HTTP status code (e.g. 200, 404)
  • response: OpenAPI response definition containing:
  • Description
  • Content types and schemas
  • Headers

func (*Operation) ResolveReferences added in v0.18.0

func (o *Operation) ResolveReferences(rootSchema *openapi3.T) error

ResolveReferences replaces all $ref references in the operation with their actual component definitions from the root schema. Returns an error if any references cannot be resolved.

type Options

type Options[HandlerFunc any, MiddlewareFunc any, Route any] struct {
	Context context.Context
	Openapi *openapi3.T
	// JSONDocumentationPath is the path exposed by json endpoint. Default to /documentation/json.
	JSONDocumentationPath string
	// YAMLDocumentationPath is the path exposed by yaml endpoint. Default to /documentation/yaml.
	YAMLDocumentationPath string
	// Add path prefix to add to every router path.
	PathPrefix string
	// FrameworkRouterFactory is a function that creates a new instance of the underlying framework router.
	// This is required when using the Host() method to manage multiple host-specific routers.
	FrameworkRouterFactory func() apirouter.Router[HandlerFunc, MiddlewareFunc, Route]
	// CustomServeHTTPHandler is an optional http.Handler that can override request handling
	// after swagger docs check but before standard routing.
	CustomServeHTTPHandler http.Handler
	// ReflectorOptions provides configuration for the jsonschema.Reflector used to generate schemas
	ReflectorOptions *jsonschema.Reflector
}

type Parameter

type Parameter struct {
	Content     Content // Media type schemas (alternative to Schema)
	Schema      *Schema // Parameter schema definition
	Description string  // Human-readable description
	Required    bool    // Whether parameter is required
}

Parameter defines an API parameter (path, query, header, cookie)

type ParameterDefinition

type ParameterDefinition struct {
	In          string  // Location (path, query, header, cookie)
	Required    bool    // Whether parameter is required
	Description string  // Human-readable description
	Content     Content // Media type schemas (alternative to Schema)
	Schema      *Schema // Parameter schema definition
}

ParameterDefinition defines a reusable parameter component

type ParameterValue

type ParameterValue map[string]Parameter

ParameterValue maps parameter names to their definitions

type Router

type Router[HandlerFunc any, MiddlewareFunc any, Route any] struct {
	// contains filtered or unexported fields
}

Router wraps framework routers while maintaining OpenAPI documentation.

Type parameters:

  • HandlerFunc: Framework-specific handler function type
  • MiddlewareFunc: Framework-specific middleware function type
  • Route: Framework-specific route type

func NewRouter

func NewRouter[HandlerFunc, MiddlewareFunc, Route any](frameworkRouter apirouter.Router[HandlerFunc, MiddlewareFunc, Route], options Options[HandlerFunc, MiddlewareFunc, Route]) (*Router[HandlerFunc, MiddlewareFunc, Route], error)

func (*Router[HandlerFunc, MiddlewareFunc, Route]) AddRawRoute

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) AddRawRoute(method string, routePath string, handler HandlerFunc, operation Operation, middleware ...MiddlewareFunc) (Route, error)

AddRawRoute adds a route with explicit OpenAPI Operation definition. This lower-level method allows full control over the OpenAPI operation definition. Parameters:

  • method: HTTP method (GET, POST, etc.)
  • routePath: URL path pattern
  • handler: Request handler function
  • operation: Predefined OpenAPI Operation
  • middleware: Optional middleware chain

Returns:

  • Route: Framework-specific route object
  • error: Validation error if operation is invalid

func (*Router[HandlerFunc, MiddlewareFunc, Route]) AddRoute

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) AddRoute(method string, path string, handler HandlerFunc, schema Definitions, middleware ...MiddlewareFunc) (Route, error)

AddRoute adds a route with OpenAPI schema inferred from Definitions. Automatically handles: - Path parameters from route path - Query parameters - Headers - Cookies - Request body - Responses Parameters:

  • method: HTTP method (GET, POST, etc.)
  • path: URL path pattern
  • handler: Request handler function
  • schema: OpenAPI definitions for the route
  • middleware: Optional middleware chain

Returns:

  • Route: Framework-specific route object
  • error: Validation error if schema is invalid

func (*Router[HandlerFunc, MiddlewareFunc, Route]) GenerateAndExposeOpenapi

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) GenerateAndExposeOpenapi() error

func (*Router[HandlerFunc, MiddlewareFunc, Route]) GetHostRouter added in v0.19.0

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) GetHostRouter(host string) *Router[HandlerFunc, MiddlewareFunc, Route]

GetHostRouter returns the host-specific router for the given host if it exists. Returns nil if no router exists for the host. Must be called on the root router instance.

func (*Router[HandlerFunc, MiddlewareFunc, Route]) GetPathPrefix added in v0.20.11

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) GetPathPrefix() string

GetPathPrefix returns the accumulated path prefix for this router. For grouped routers, this includes all parent prefixes joined together.

func (*Router[HandlerFunc, MiddlewareFunc, Route]) GetRootRouter added in v0.19.0

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) GetRootRouter() *Router[HandlerFunc, MiddlewareFunc, Route]

GetRootRouter returns the root router instance that this router belongs to. For the root router itself, it returns itself.

func (*Router[HandlerFunc, MiddlewareFunc, Route]) GetSwaggerSchema added in v0.20.2

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) GetSwaggerSchema() *openapi3.T

SwaggerSchema returns the OpenAPI schema associated with this router instance. For host-specific routers, this returns the host's isolated schema. For subrouters, this returns the shared schema from their parent.

func (*Router[HandlerFunc, MiddlewareFunc, Route]) Group added in v0.12.0

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) Group(pathPrefix string) (*Router[HandlerFunc, MiddlewareFunc, Route], error)

Group creates a new router group with prefix and optional group-level middleware. Routes added to the returned router will inherit the parent's host and append the path prefix. Group creates a new router group with the given path prefix. Routes added to the group will have their paths prefixed with group's path. The group inherits the parent's host and shares the root OpenAPI schema. Returns an error if pathPrefix is invalid.

func (*Router[HandlerFunc, MiddlewareFunc, Route]) Host added in v0.16.0

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) Host(host string) (*Router[HandlerFunc, MiddlewareFunc, Route], error)

Host creates a new router instance configured for a specific host. This method must be called on the root router instance. Routes added to the returned router will only match requests for the specified host and will be documented with a server object for that host. Host creates a new router instance configured for a specific host. The host router maintains its own isolated OpenAPI schema while sharing documentation paths and context with the root router. Must be called on the root router instance. Returns an error if: - Called on non-root router - Host is empty - FrameworkRouterFactory is not set

func (*Router[HandlerFunc, MiddlewareFunc, Route]) Router

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) Router() apirouter.Router[HandlerFunc, MiddlewareFunc, Route]

Router returns the underlying router implementation for the current context (default, group, or host) Router returns the underlying framework-specific router instance. This allows accessing framework-specific functionality when needed.

func (*Router[HandlerFunc, MiddlewareFunc, Route]) ServeHTTP added in v0.16.0

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP handles HTTP requests with the following precedence: 1. Checks for swagger documentation requests 2. Calls customServeHTTPHandler if set 3. Attempts host-specific routing if available 4. Falls back to root router Returns 500 if called on non-root router

func (*Router[HandlerFunc, MiddlewareFunc, Route]) SetInfo added in v0.17.2

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) SetInfo(info *openapi3.Info) *Router[HandlerFunc, MiddlewareFunc, Route]

SetInfo sets the OpenAPI Info struct (title, version, description etc) for the router. This allows modifying the API metadata after router creation. Returns the router instance for method chaining. If info is nil, the method is a no-op and returns the router unchanged.

func (*Router[HandlerFunc, MiddlewareFunc, Route]) SubRouter

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) SubRouter(router apirouter.Router[HandlerFunc, MiddlewareFunc, Route], opts SubRouterOptions) (*Router[HandlerFunc, MiddlewareFunc, Route], error)

SubRouter creates a new router with the given path prefix. The new router shares the same OpenAPI schema and documentation paths as the parent, but routes are prefixed with the specified path.

func (*Router[HandlerFunc, MiddlewareFunc, Route]) SwaggerSchema

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) SwaggerSchema(schema *openapi3.T) *Router[HandlerFunc, MiddlewareFunc, Route]

SwaggerSchema sets the OpenAPI schema for the router instance. This allows modifying the schema after router creation, particularly useful for host-specific routers where you want to customize the schema. Returns the router instance for method chaining.

func (*Router[HandlerFunc, MiddlewareFunc, Route]) Use added in v0.14.0

func (r *Router[HandlerFunc, MiddlewareFunc, Route]) Use(middleware ...MiddlewareFunc)

Use adds middleware to the router that will be executed for all routes registered on this router instance. Middleware executes in the order they are added.

type Schema

type Schema struct {
	Value                     any  // Go type to generate schema from
	AllowAdditionalProperties bool // Whether to allow extra fields
}

Schema defines the structure of request/response data

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement maps security scheme names to required scopes

type SecurityRequirements

type SecurityRequirements []SecurityRequirement

SecurityRequirements lists required security schemes

type SubRouterOptions

type SubRouterOptions struct {
	PathPrefix string
}

Router provides API routing with integrated OpenAPI schema generation. Supports multiple router implementations (gorilla/mux, fiber, echo) with: - Host-specific routing with isolated schemas - Route grouping by path prefixes - Middleware chaining - Automatic OpenAPI documentation generation

Directories

Path Synopsis
support

Jump to

Keyboard shortcuts

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