chioas

package module
v1.16.3 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2024 License: Apache-2.0 Imports: 25 Imported by: 0

README

CHIOAS

GoDoc Latest Version Go Report Card

Chioas is an add-on for the popular Chi router

pronounce Chioas however you like...

but I can't help feeling that it looks a little like "chaos" - the chaos of undocumented APIs that it tries to solve!

What it does

Chioas does three things:

  • Defines your API as a single (or modular) struct and then builds the Chi routes accordingly
  • Produces an OpenApi spec (OAS) of that definition
  • Optionally serves an interactive API docs web-page (as part of your service)
Advantages

With your actual API and OpenAPI spec (OAS) being specified in one place there's no chance of them becoming out of sync! (eliminating having to manually update spec yaml/json to match API or vice versa)

You can even keep your request/response OAS schemas in sync with your request/response structs!
See petstore example

Already have an OAS spec?

No problem, use chioas.FromJson() or chioas.FromYaml() to read the spec definition. All you'll need to do is add x-handler tags to each method in the spec.

See From example

Choice of UI styles

Chioas supports two different styles of API docs UI:

  1. Redoc (see Redocly.redoc and Redoc-try)
  2. Swagger (see swagger-ui)
  3. Rapidoc (see rapidoc)

Set the desired style using DocOptions.UIStyle (the default is Redoc). Notes:

  • statics for Redoc are served from CDNs
  • statics for Swagger are all served directly from Chioas
  • statics for Rapidoc are all served directly from Chioas

Chioas also supports serving multiple styles of UI on different docs paths (see DocOptions.AlternateUIDocs and example)

Added Bonus Features

Chioas comes with many bonus features that help in building complete APIs and specs...

  • Highly extensible - e.g. if there are parts of the OAS spec that are not directly supported by Chioas, then they can be added using the Additional field on each part
  • Optionally check that OAS refs ($ref) are valid (see DocOptions.CheckRefs)
  • Optional typed handlers - see typed README
  • Optional automatically added HEAD methods for GET methods (see Definition.AutoHeadMethods)
  • Optional automatically added OPTIONS methods - with Allow header populated with actual allowed methods (see Definition.AutoOptionsMethods and Path.AutoOptionsMethod)
  • Optional automatically added Chi MethodNotAllowed handler to each path - with Allow header populated with actual allowed methods (see Definition.AutoMethodNotAllowed)

Installation

To install chioas, use go get:

go get github.com/go-andiamo/chioas

To update chioas to the latest version, run:

go get -u github.com/go-andiamo/chioas

Basic Example

package main

import (
    "github.com/go-andiamo/chioas"
    "github.com/go-chi/chi/v5"
    "net/http"
)

func main() {
    router := chi.NewRouter()
    if err := myApi.SetupRoutes(router, myApi); err != nil {
        panic(err)
    }
    _ = http.ListenAndServe(":8080", router)
}

var myApi = chioas.Definition{
    AutoHeadMethods: true,
    DocOptions: chioas.DocOptions{
        ServeDocs:       true,
        HideHeadMethods: true,
    },
    Paths: chioas.Paths{
        "/foos": {
            Methods: chioas.Methods{
                http.MethodGet: {
                    Handler: getFoos,
                    Responses: chioas.Responses{
                        http.StatusOK: {
                            Description: "List of foos",
                            IsArray:     true,
                            SchemaRef:   "foo",
                        },
                    },
                },
                http.MethodPost: {
                    Handler: postFoos,
                    Request: &chioas.Request{
                        Description: "Foo to create",
                        SchemaRef:   "foo",
                    },
                    Responses: chioas.Responses{
                        http.StatusCreated: {
                            Description: "New foo",
                            SchemaRef:   "foo",
                        },
                    },
                },
                http.MethodHead: {
                    Handler: getFoos,
                },
            },
            Paths: chioas.Paths{
                "/{fooId}": {
                    Methods: chioas.Methods{
                        http.MethodGet: {
                            Handler: getFoo,
                            Responses: chioas.Responses{
                                http.StatusOK: {
                                    Description: "The foo",
                                    SchemaRef:   "foo",
                                },
                            },
                        },
                        http.MethodDelete: {
                            Handler: deleteFoo,
                        },
                    },
                },
            },
        },
    },
    Components: &chioas.Components{
        Schemas: chioas.Schemas{
            {
                Name:               "foo",
                RequiredProperties: []string{"name", "address"},
                Properties:         chioas.Properties{
                    {
                        Name: "name",
                        Type: "string",
                    },
                    {
                        Name: "address",
                        Type: "string",
                    },
                },
            },
        },
    },
}

func getFoos(writer http.ResponseWriter, request *http.Request) {
}

func postFoos(writer http.ResponseWriter, request *http.Request) {
}

func getFoo(writer http.ResponseWriter, request *http.Request) {
}

func deleteFoo(writer http.ResponseWriter, request *http.Request) {
}

Run and then check out http://localhost:8080/docs !

Or simply generate the OpenAPI spec...

package main

import (
    "net/http"

    "github.com/go-andiamo/chioas"
)

func main() {
    data, _ := myApi.AsYaml()
    println(string(data))
}

var myApi = chioas.Definition{
    AutoHeadMethods: true,
    DocOptions: chioas.DocOptions{
        ServeDocs:       true,
        HideHeadMethods: true,
    },
    Paths: chioas.Paths{
        "/foos": {
            Methods: chioas.Methods{
                http.MethodGet: {
                    Handler: getFoos,
                    Responses: chioas.Responses{
                        http.StatusOK: {
                            Description: "List of foos",
                            IsArray:     true,
                            SchemaRef:   "foo",
                        },
                    },
                },
                http.MethodPost: {
                    Handler: postFoos,
                    Request: &chioas.Request{
                        Description: "Foo to create",
                        SchemaRef:   "foo",
                    },
                    Responses: chioas.Responses{
                        http.StatusCreated: {
                            Description: "New foo",
                            SchemaRef:   "foo",
                        },
                    },
                },
                http.MethodHead: {
                    Handler: getFoos,
                },
            },
            Paths: chioas.Paths{
                "/{fooId}": {
                    Methods: chioas.Methods{
                        http.MethodGet: {
                            Handler: getFoo,
                            Responses: chioas.Responses{
                                http.StatusOK: {
                                    Description: "The foo",
                                    SchemaRef:   "foo",
                                },
                            },
                        },
                        http.MethodDelete: {
                            Handler: deleteFoo,
                        },
                    },
                },
            },
        },
    },
    Components: &chioas.Components{
        Schemas: chioas.Schemas{
            {
                Name:               "foo",
                RequiredProperties: []string{"name", "address"},
                Properties: chioas.Properties{
                    {
                        Name: "name",
                        Type: "string",
                    },
                    {
                        Name: "address",
                        Type: "string",
                    },
                },
            },
        },
    },
}

func getFoos(writer http.ResponseWriter, request *http.Request) {
}

func postFoos(writer http.ResponseWriter, request *http.Request) {
}

func getFoo(writer http.ResponseWriter, request *http.Request) {
}

func deleteFoo(writer http.ResponseWriter, request *http.Request) {
}

try on go-playground

Documentation

Overview

Package chioas - Go package for building OAS (OpenApi Specs) for Chi APIs

Index

Constants

This section is empty.

Variables

MethodsOrder defines the order in which methods appear in docs

View Source
var OasVersion = "3.0.3"

OasVersion is the default OAS version for docs

Functions

func SourceComment added in v1.6.0

func SourceComment(comments ...string) string

SourceComment is a utility function that can be used to place a comment in the spec yaml informing where, in the source code, a particular spec item was defined. Example:

	var myApi = chioas.Definition{
	  Comment:         chioas.SourceComment("this is a static comment"),
   ...

Types

type Additional

type Additional interface {
	Write(on any, w yaml.Writer)
}

Additional is an interface that can be supplied to many parts of the definition to write additional yaml to the OAS

type AdditionalOasProperties added in v1.13.5

type AdditionalOasProperties map[string]any

AdditionalOasProperties is a type (map) of additional OAS properties that can be used for use on any .Additional property

func (AdditionalOasProperties) Write added in v1.13.5

func (ap AdditionalOasProperties) Write(on any, w yaml.Writer)

type AlternateUIDoc added in v1.16.0

type AlternateUIDoc struct {
	// DocIndexPage the name of the docs index page (defaults to "index.html")
	DocIndexPage string
	// SupportFiles is an optional handler that is used for other files under "/docs" path
	//
	// see _examples/swagger_ui for example usage
	SupportFiles http.Handler
	// SupportFilesStripPrefix if set to true (and SupportFiles is specified) then
	// calls to SupportFiles have the "/docs" path prefix stripped from the http.Request
	SupportFilesStripPrefix bool
	// Title the title in the docs index page (defaults to "API Documentation")
	Title string
	// UIStyle is the style of the API docs UI
	//
	// use Redoc, Swagger or Rapidoc (defaults to Redoc)
	UIStyle UIStyle
	// RedocOptions redoc options to be used (see https://github.com/Redocly/redoc#redoc-options-object)
	//
	// use map[string]any or &RedocOptions or anything that implements ToMap (or anything that can be marshalled and then unmarshalled to map[string]any)
	//
	// Only used if DocOptions.UIStyle is Redoc
	RedocOptions any
	// SwaggerOptions swagger-ui options to be used (see https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md)
	//
	// Only used if DocOptions.UIStyle is Swagger
	SwaggerOptions any
	// RapidocOptions rapidoc options to be used
	//
	// Only used if DocOptions.UIStyle is Rapidoc
	RapidocOptions any
	// SpecName the name of the OAS spec (defaults to "spec.yaml")
	SpecName string
	// DocTemplate template for the docs page (defaults to internal template if an empty string)
	DocTemplate string
	// StylesOverride css styling overrides (injected into docs index page)
	StylesOverride string
	// RedocJsUrl is the URL for the Redoc JS
	//
	// defaults to:
	// https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.77/bundles/redoc.standalone.min.js
	//
	// Only used if DocOptions.UIStyle is Redoc
	RedocJsUrl string
	// TryJsUrl is the URL for the Try Redoc JS
	//
	// defaults to:
	// https://cdn.jsdelivr.net/gh/wll8/redoc-try@1.4.7/dist/try.js
	//
	// Only used if DocOptions.UIStyle is Redoc
	TryJsUrl string
	// Middlewares is any chi.Middlewares for everything served under this docs path
	Middlewares chi.Middlewares
	// NoCache if set to true, docs page and spec aren't cached (and built on each call)
	NoCache bool
	// AsJson if set to true, serves the spec as JSON
	AsJson bool
}

type AlternateUIDocs added in v1.16.0

type AlternateUIDocs map[string]AlternateUIDoc

type ApplyMiddlewares added in v1.1.2

type ApplyMiddlewares func(thisApi any) chi.Middlewares

ApplyMiddlewares is a function that returns middlewares to be applied to a Path or the api root

can be used on Path.ApplyMiddlewares and Definition.ApplyMiddlewares (for api root)

type CommonParameter added in v1.5.0

type CommonParameter struct {
	// Name is the name of the param
	Name string
	// Description is the OAS description
	Description string
	// Required is the OAS required flag
	Required bool
	// In is the OAS field defining whether the param is a "query", "header", "path" or "cookie" param
	//
	// Defaults to "query"
	In string
	// Example is the OAS example for the param
	Example any
	// Schema is the optional OAS Schema
	Schema *Schema
	// SchemaRef is the OAS schema reference
	//
	// Only used if value is a non-empty string - if both Schema is nil and SchemaRef is empty string, then an
	// empty object schema is written to the spec yaml, e.g.
	//   schema:
	//     type: "object"
	//
	// If the value does not contain a path (i.e. does not contain any "/") then the ref
	// path will be the value prefixed with components schemas path.  For example, specifying "foo"
	// will result in a schema ref:
	//   schema:
	//     $ref: "#/components/schemas/foo"
	SchemaRef string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

CommonParameter represents the OAS definition of a reusable parameter (as used by Components.Parameters)

type CommonParameters added in v1.5.0

type CommonParameters map[string]CommonParameter

CommonParameters is a map of CommonParameter, where the key is the name (that can be referenced by PathParam.Ref or QueryParam.Ref)

type CommonRequests added in v1.4.0

type CommonRequests map[string]Request

CommonRequests is a map of Request, where the key is the name (that can be referenced by Request.Ref)

type CommonResponses added in v1.4.0

type CommonResponses map[string]Response

CommonResponses is a map of Response, where the key is the name (that can be referenced by Response.Ref)

type Components

type Components struct {
	// Schemas is the OAS reusable schemas
	Schemas Schemas
	// Requests is the OAS reusable requests
	//
	// To reference one of these, use Method.Request.Ref with the name
	Requests CommonRequests
	// Responses is the OAS reusable responses
	//
	// To reference one of these, use Method.Response.Ref with the name
	Responses CommonResponses
	// Examples is the OAS reusable examples
	//
	// To reference one of these, use Example.Ref with the name
	Examples Examples
	// Parameters is the OAS reusable parameters
	Parameters CommonParameters
	// SecuritySchemes is the OAS security schemes
	SecuritySchemes SecuritySchemes
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

Components represents the OAS components

type Constraints added in v1.7.0

type Constraints struct {
	Pattern          string
	Maximum          json.Number
	Minimum          json.Number
	ExclusiveMaximum bool
	ExclusiveMinimum bool
	Nullable         bool
	MultipleOf       uint
	MaxLength        uint
	MinLength        uint
	MaxItems         uint
	MinItems         uint
	UniqueItems      bool
	MaxProperties    uint
	MinProperties    uint
	// Additional is any other OAS constraints for a property (that are not currently defined in Constraints)
	Additional map[string]any
}

Constraints defines the constraints for an OAS property

type Contact

type Contact struct {
	Name  string
	Url   string
	Email string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

Contact represents the OAS contact section of the info

type ContentType added in v1.7.0

type ContentType struct {
	// Schema is the optional OAS Schema
	//
	// Only used if the value is non-nil - otherwise uses SchemaRef is used
	//
	// The value can be any of the following:
	//
	// * chioas.Schema (or *chioas.Schema)
	//
	// * a chioas.SchemaConverter
	//
	// * a chioas.SchemaWriter
	//
	// * a struct or ptr to struct (schema written is determined by examining struct fields)
	//
	// * a slice of structs (items schema written is determined by examining struct fields)
	Schema any
	// SchemaRef is the OAS schema reference
	//
	// Only used if value is a non-empty string - if both Schema is nil and SchemaRef is empty string, then an
	// empty object schema is written to the spec yaml, e.g.
	//   schema:
	//     type: "object"
	//
	// If the value does not contain a path (i.e. does not contain any "/") then the ref
	// path will be the value prefixed with components schemas path.  For example, specifying "foo"
	// will result in a schema ref:
	//   schema:
	//     $ref: "#/components/schemas/foo"
	SchemaRef string
	// IsArray indicates that request is an array of items
	IsArray bool
	// Examples is the ordered list of examples for the content type
	Examples Examples
}

type ContentTypes added in v1.7.0

type ContentTypes map[string]ContentType

ContentTypes is used by Response.AlternativeContentTypes and Request.AlternativeContentTypes to denote alternative content types

The key is a media type - e.g. "application/json"

type Definition

type Definition struct {
	// DocOptions is the documentation options for the spec
	DocOptions DocOptions
	// Info is the OAS info for the spec
	Info Info
	// Servers is the OAS servers for the spec
	Servers Servers
	// Tags is the OAS tags for the spec
	Tags Tags
	// Methods is any methods on the root api
	Methods Methods
	// Middlewares is any chi.Middlewares for api root
	Middlewares chi.Middlewares
	// ApplyMiddlewares is an optional function that returns chi.Middlewares for api root
	ApplyMiddlewares ApplyMiddlewares
	// Paths is the api paths to be setup (each path can have sub-paths)
	Paths Paths // descendant paths
	// Components is the OAS components
	Components *Components
	// Security is the OAS security for the api
	Security SecuritySchemes
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
	// AutoHeadMethods when set to true, automatically adds HEAD methods for GET methods (where HEAD method not explicitly specified)
	//
	// If you don't want these automatically added HEAD methods to appear in the OAS spec - then set DocOptions.HideAutoOptionsMethods
	AutoHeadMethods bool
	// AutoOptionsMethods when set to true, automatically adds OPTIONS methods for each path (and because Chioas knows the methods for each path can correctly set the Allow header)
	//
	// Note: If an OPTIONS method is already defined for the path then no OPTIONS method is automatically added
	AutoOptionsMethods bool
	// OptionsMethodPayloadBuilder is an optional implementation of OptionsMethodPayloadBuilder that can provide body payloads for the automatically created OPTIONS methods
	OptionsMethodPayloadBuilder OptionsMethodPayloadBuilder
	// RootAutoOptionsMethod when set to true, automatically adds OPTIONS method for the root path (and because Chioas knows the methods for each path can correctly set the Allow header)
	//
	// Note: If an OPTIONS method is already defined for the root path then no OPTIONS method is automatically added
	RootAutoOptionsMethod bool
	// AutoMethodNotAllowed when set to true, automatically adds a method not allowed (405) handler for each path (and because Chioas knows the methods for each path can correctly set the Allow header)
	AutoMethodNotAllowed bool
	// MethodHandlerBuilder is an optional MethodHandlerBuilder which is called to build the
	// http.HandlerFunc for the method
	//
	// If MethodHandlerBuilder is nil then the default method handler builder is used
	MethodHandlerBuilder MethodHandlerBuilder
}

Definition is the overall definition of an api

func FromJson added in v1.8.0

func FromJson(r io.Reader, opts *FromOptions) (result *Definition, err error)

FromJson builds a Definition from an existing OAS spec JSON

where all methods in the spec must have a `x-handler` property, e.g.

"paths": {
  "/": {
    "get": {
      "x-handler": "getRoot"
      ...

where the key "getRoot" must be provided in the handlers arg

or...

"paths": {
  "/": {
    "get": {
      "x-handler": ".GetRoot"
      ...

where the "GetRoot" must be a http.HandlerFunc method on the supplied api arg

func FromYaml added in v1.8.0

func FromYaml(r io.Reader, opts *FromOptions) (result *Definition, err error)

FromYaml builds a Definition from an existing OAS spec YAML

where all methods in the spec must have a `x-handler` tag, e.g.

paths:
  "/":
    get:
      x-handler: "getRoot"

where the key "getRoot" must be provided in the handlers arg

or...

paths:
  "/":
    get:
      x-handler: ".GetRoot"

where the "GetRoot" must be a http.HandlerFunc method on the supplied api arg

func (*Definition) AsJson added in v1.6.1

func (d *Definition) AsJson() (data []byte, err error)

AsJson returns the spec as JSON data

func (*Definition) AsYaml

func (d *Definition) AsYaml() ([]byte, error)

AsYaml returns the spec as YAML data

func (*Definition) RefCheck added in v1.8.3

func (d *Definition) RefCheck(area, ref string) error

RefCheck implements yaml.RefChecker checks that refs specified exist in Definition.Components (if DocOptions.CheckRefs is set to true)

func (*Definition) SetupRoutes

func (d *Definition) SetupRoutes(router chi.Router, thisApi any) error

SetupRoutes sets up the API routes on the supplied chi.Router

Pass the thisApi arg if any of the methods use method by name

func (*Definition) WriteJson added in v1.6.1

func (d *Definition) WriteJson(writer io.Writer) (err error)

WriteJson writes the definition as JSON to the provided io.Writer

func (*Definition) WriteYaml

func (d *Definition) WriteYaml(w io.Writer) error

WriteYaml writes the definition as YAML to the provided io.Writer

type DisablerFunc added in v1.16.1

type DisablerFunc func() bool

DisablerFunc is a function that can be used by Path.Disabled

type Discriminator added in v1.11.0

type Discriminator struct {
	// PropertyName is the OAS property name for the discriminator
	PropertyName string
	// Mapping holds mappings between payload values (of the specified property) and schema names or references
	Mapping map[string]string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

Discriminator is a representation of the OAS discriminator object

type DocOptions

type DocOptions struct {
	// ServeDocs whether to serve api docs
	ServeDocs bool
	// Context is the optional path prefix for all paths in OAS spec
	Context string
	// NoCache if set to true, docs page and spec aren't cached (and built on each call)
	NoCache bool
	// AsJson if set to true, serves the spec as JSON
	AsJson bool
	// Path the path on which to serve api docs page and spec (defaults to "/docs")
	Path string
	// DocIndexPage the name of the docs index page (defaults to "index.html")
	DocIndexPage string
	// SupportFiles is an optional handler that is used for other files under "/docs" path
	//
	// see _examples/swagger_ui for example usage
	SupportFiles http.Handler
	// SupportFilesStripPrefix if set to true (and SupportFiles is specified) then
	// calls to SupportFiles have the "/docs" path prefix stripped from the http.Request
	SupportFilesStripPrefix bool
	// Title the title in the docs index page (defaults to "API Documentation")
	Title string
	// UIStyle is the style of the API docs UI
	//
	// use Redoc, Swagger or Rapidoc (defaults to Redoc)
	UIStyle UIStyle
	// AlternateUIDocs allow your docs UI to be served as different styles on different paths
	//
	// where the key for each is the docs path
	AlternateUIDocs AlternateUIDocs
	// RedocOptions redoc options to be used (see https://github.com/Redocly/redoc#redoc-options-object)
	//
	// use map[string]any or &RedocOptions or anything that implements ToMap (or anything that can be marshalled and then unmarshalled to map[string]any)
	//
	// Only used if DocOptions.UIStyle is Redoc
	RedocOptions any
	// SwaggerOptions swagger-ui options to be used (see https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md)
	//
	// Only used if DocOptions.UIStyle is Swagger
	SwaggerOptions any
	// RapidocOptions rapidoc options to be used
	//
	// Only used if DocOptions.UIStyle is Rapidoc
	RapidocOptions any
	// SpecName the name of the OAS spec (defaults to "spec.yaml")
	SpecName string
	// DocTemplate template for the docs page (defaults to internal template if an empty string)
	DocTemplate string
	// StylesOverride css styling overrides (injected into docs index page)
	StylesOverride string
	// RedocJsUrl is the URL for the Redoc JS
	//
	// defaults to:
	// https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.77/bundles/redoc.standalone.min.js
	//
	// Only used if DocOptions.UIStyle is Redoc
	RedocJsUrl string
	// TryJsUrl is the URL for the Try Redoc JS
	//
	// defaults to:
	// https://cdn.jsdelivr.net/gh/wll8/redoc-try@1.4.7/dist/try.js
	//
	// Only used if DocOptions.UIStyle is Redoc
	TryJsUrl string
	// DefaultResponses is the default responses for methods that don't have any responses defined
	//
	// is a map of http status code and response
	DefaultResponses Responses
	// HideHeadMethods indicates that all HEAD methods should be hidden from docs
	HideHeadMethods bool
	// HideAutoOptionsMethods indicates that automatically added OPTIONS methods (see Definition.AutoOptionsMethods) are hidden from docs
	HideAutoOptionsMethods bool
	// OperationIdentifier is an optional function called by Method to generate `operationId` tag value
	OperationIdentifier OperationIdentifier
	// Middlewares is any chi.Middlewares for everything served under '/docs' path
	Middlewares chi.Middlewares
	// CheckRefs when set to true, all internal $ref's are checked
	CheckRefs bool
	// contains filtered or unexported fields
}

DocOptions determines whether/how the api will serve interactive docs page

func (*DocOptions) SetupRoutes added in v1.8.2

func (d *DocOptions) SetupRoutes(def *Definition, route chi.Router) error

type Example added in v1.11.0

type Example struct {
	// Name is the name of the example (must be specified)
	Name string
	// Summary is the OAS summary of the example
	Summary string
	// Description is the OAS description of the example
	Description string
	// Value os the OAS value for the example
	Value any
	// ExampleRef is the OAS example reference
	//
	// Only used if value is a non-empty string
	//
	// If the value does not contain a path (i.e. does not contain any "/") then the ref
	// path will be the value prefixed with components example path.  For example, specifying "foo"
	// will result in a schema ref:
	//   "my example":
	//     $ref: "#/components/examples/foo"
	ExampleRef string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml (not used with Ref)
	Comment string
}

type Examples added in v1.11.0

type Examples []Example

type Extensions added in v1.3.0

type Extensions map[string]any

Extensions can be added to many OAS items and are written as `x-` yaml properties

type ExternalDocs

type ExternalDocs struct {
	Description string
	Url         string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

ExternalDocs represents the OAS external docs for a spec

type FavIcons added in v1.16.1

type FavIcons map[int]string

FavIcons is a map of icon size and fav icon filename

Used by SwaggerOptions.FavIcons, RedocOptions.FavIcons and RapidocOptions.FavIcons

type FromOptions added in v1.8.0

type FromOptions struct {
	// DocOptions is the optional doc options for the generated Definition
	DocOptions *DocOptions
	// Api is the optional api object that provides methods where `x-handler` is specified as ".HandlerMethodName"
	Api any
	// Handlers is the optional look for handlers specified by `x-handler`
	Handlers Handlers
	// Strict when set, causes the FromJson / FromYaml to error if no `x-handler` tag is specified
	Strict bool
	// PathMiddlewares is an optional func that sets middlewares on paths found in the from spec
	PathMiddlewares PathMiddlewares
}

FromOptions is used by FromJson and FromYaml to control how the definition is built from a pre-existing OAS spec

type GetHandler added in v1.3.0

type GetHandler func(path string, method string, thisApi any) (http.HandlerFunc, error)

GetHandler is a function that can be set on Method.Handler - and is called to obtain the http.HandlerFunc

type Handlers added in v1.8.0

type Handlers map[string]http.HandlerFunc

Handlers is a lookup, by name, used by FromJson or FromYaml

type Info

type Info struct {
	// Title is the OAS title
	Title string
	// Description is the OAS description
	Description string
	// Version is the OAS version (of the api)
	Version string
	// TermsOfService is the OAS terms of service
	TermsOfService string
	// Contact is the optional OAS contact info
	Contact *Contact
	// License is the optional OAS license info
	License *License
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// ExternalDocs is the optional eternal docs (for the entire spec)
	ExternalDocs *ExternalDocs
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

Info represents the OAS info section of the spec

type License

type License struct {
	Name string
	Url  string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

License represents the OAS license section of the info

type MappableOptions added in v1.9.0

type MappableOptions interface {
	ToMap() map[string]any
}

MappableOptions is an interface that can be used by either DocOptions.RedocOptions or DocOptions.SwaggerOptions and converts the options to a map (as used by the HTML template)

type Method

type Method struct {
	// Description is the OAS description of the method
	Description string
	// Summary is the OAS summary of the method
	Summary string
	// Handler is the http.HandlerFunc to be used by Chi
	//
	// Can also be specified as a string - which must be a public method on the interface passed to Definition.SetupRoutes
	//
	// Can also be specified as a method expression - e.g
	//   Handler: (*myApi).GetSomething
	// (the method specified must be a public method on the interface passed to Definition.SetupRoutes
	//
	// Can also be specified as a GetHandler func - which is called to acquire the http.HandlerFunc
	Handler any
	// OperationId is the OAS operation id of the method
	//
	// This can be overridden by providing a DocOptions.OperationIdentifier
	OperationId string
	// Tag is the OAS tag of the method
	//
	// If this is an empty string and any ancestor Path.Tag is set then that ancestor tag is used
	Tag string
	// QueryParams is the OAS query params for the method
	//
	// Can also be used to specify header params (see QueryParam.In)
	QueryParams QueryParams
	// Request is the optional OAS request body for the method
	Request *Request
	// Responses is the OAS responses for the method
	//
	// If no responses are specified, the DocOptions.DefaultResponses is used
	//
	// If there are no DocOptions.DefaultResponses specified, then a http.StatusOK response is used
	Responses Responses
	// Deprecated is the OAS deprecated flag for the method
	Deprecated bool
	// Security is the OAS security schemes used by the method
	Security SecuritySchemes
	// OptionalSecurity if set to true, adds an entry to the OAS method security e.g.
	//  security:
	//   - {}
	OptionalSecurity bool
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
	// HideDocs if set to true, hides this method from the OAS docs
	HideDocs bool
}

Method represents the definition of a method (as used by Path and, for root methods, Definition)

type MethodHandlerBuilder added in v1.10.0

type MethodHandlerBuilder interface {
	BuildHandler(path string, method string, mdef Method, thisApi any) (http.HandlerFunc, error)
}

type Methods

type Methods map[string]Method

Methods is a map of Method (where the key is a http.Method)

type OfRef added in v1.11.0

type OfRef string

func (OfRef) IsRef added in v1.11.0

func (o OfRef) IsRef() bool

func (OfRef) Ref added in v1.11.0

func (o OfRef) Ref() string

func (OfRef) Schema added in v1.11.0

func (o OfRef) Schema() *Schema

type OfSchema added in v1.11.0

type OfSchema interface {
	IsRef() bool
	Ref() string
	Schema() *Schema
}

type OfType added in v1.11.0

type OfType uint
const (
	OneOf OfType = iota
	AnyOf
	AllOf
)

func (OfType) TagName added in v1.11.0

func (ot OfType) TagName() string

type Ofs added in v1.11.0

type Ofs struct {
	// OfType is the type - can be OneOf (default), AnyOf or AllOf
	OfType OfType
	// Of is the ordered slice of OfSchema items
	//
	// an OfSchema can be either a *Schema or an OfRef
	//
	// Note: the Ofs will not be written if the Of is empty!
	Of []OfSchema
}

Ofs is a representation of OAS oneOf, allOf or anyOf

type OperationIdentifier added in v1.1.3

type OperationIdentifier func(method Method, methodName string, path string, parentTag string) string

OperationIdentifier is a function that can be provided to DocOptions

type OptionsMethodPayloadBuilder added in v1.13.4

type OptionsMethodPayloadBuilder interface {
	BuildPayload(path string, pathDef *Path, def *Definition) (data []byte, headers map[string]string)
}

OptionsMethodPayloadBuilder is an interface that can be provided to Definition.OptionsMethodPayloadBuilder and allows automatically created OPTIONS methods to return a body payload

func NewRootOptionsMethodPayloadBuilder added in v1.13.4

func NewRootOptionsMethodPayloadBuilder() OptionsMethodPayloadBuilder

NewRootOptionsMethodPayloadBuilder provides an OptionsMethodPayloadBuilder that can be used for Definition.OptionsMethodPayloadBuilder and provides the OPTIONS payload body on API root as the OAS spec

type OptionsWithFavIcons added in v1.16.1

type OptionsWithFavIcons interface {
	GetFavIcons() FavIcons
}

type Path

type Path struct {
	// Methods is the methods on the path
	Methods Methods
	// Paths is the sub-paths of the path
	Paths Paths
	// Middlewares is any chi.Middlewares for the path
	Middlewares chi.Middlewares
	// ApplyMiddlewares is an optional function that returns chi.Middlewares for the path
	ApplyMiddlewares ApplyMiddlewares
	// Tag is the OAS tag of the path
	//
	// If this is an empty string and any ancestor Path.Tag is set then that ancestor tag is used
	//
	// The final tag is used by Method
	Tag string
	// PathParams is the OAS information about path params on this path
	//
	// Any path params introduced in the path are descended down the sub-paths and methods - any
	// path params that are not documented will still be seen in the OAS spec for methods
	PathParams PathParams
	// HideDocs if set to true, hides this path (and descendants) from docs
	HideDocs bool
	// Disabled is an optional DisablerFunc that, when called, returns whether this path is to be disabled
	//
	// When a path is disabled it does not appear in docs and is not registered on the router
	Disabled DisablerFunc
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
	// AutoOptionsMethod when set to true, automatically adds OPTIONS method for the path (and because Chioas knows the methods for each path can correctly set the Allow header)
	//
	// Note: If an OPTIONS method is already defined for the path then no OPTIONS method is automatically added
	AutoOptionsMethod bool
}

Path represents a path for both the router and the OAS spec

type PathMiddlewares added in v1.8.0

type PathMiddlewares func(path string) chi.Middlewares

type PathParam

type PathParam struct {
	// Description is the OAS description
	Description string
	// Example is the OAS example
	Example any
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml (not used with Ref)
	Comment string
	// Schema is the optional OAS Schema
	Schema *Schema
	// SchemaRef is the OAS schema reference
	//
	// Only used if value is a non-empty string - if both Schema is nil and SchemaRef is empty string, then an
	// empty object schema is written to the spec yaml, e.g.
	//   schema:
	//     type: "string"
	//
	// If the value does not contain a path (i.e. does not contain any "/") then the ref
	// path will be the value prefixed with components schemas path.  For example, specifying "foo"
	// will result in a schema ref:
	//   schema:
	//     $ref: "#/components/schemas/foo"
	SchemaRef string
	// Ref is the OAS $ref name for the parameter
	//
	// If this is a non-empty string, then a $ref to "#/components/parameters/" is used
	Ref string
}

PathParam represents the OAS definition of a path param

type PathParams

type PathParams map[string]PathParam

PathParams is a map of PathParam where the key is the param name

type Paths

type Paths map[string]Path

type Properties added in v1.4.0

type Properties []Property

Properties is an ordered collection of Property

type Property

type Property struct {
	// Name is the OAS name of the property
	Name string
	// Description is the OAS description of the property
	Description string
	// Type is the OAS type of the property
	//
	// Should be one of "string", "object", "array", "boolean", "integer", "number" or "null"
	Type string
	// ItemType is the OAS type of array items
	//
	// only used if Type = "array"
	ItemType string
	// Properties is the ordered collection of sub-properties
	//
	// Only used if Type == "object" (or Type == "array" and ItemType == "object"
	Properties Properties
	// Required indicates the property is required
	//
	// see also Schema.RequiredProperties
	Required bool
	// Format is the OAS format for the property
	Format string
	// Example is the OAS example for the property
	Example any
	// Enum is the OAS enum of the property
	Enum []any
	// Deprecated is the OAS deprecated flag for the property
	Deprecated bool
	// Constraints is the OAS constraints for the property
	Constraints Constraints
	// SchemaRef is the OAS schema reference
	//
	// Only used if value is a non-empty string
	//
	// If the value does not contain a path (i.e. does not contain any "/") then the ref
	// path will be the value prefixed with components schemas path.  For example, specifying "foo"
	// will result in a schema ref:
	//   schema:
	//     $ref: "#/components/schemas/foo"
	SchemaRef string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

Property represents the OAS definition of a property

type QueryParam

type QueryParam struct {
	// Name is the name of the param
	Name string
	// Description is the OAS description
	Description string
	// Required is the OAS required flag
	Required bool
	// In is the OAS field defining whether the param is a "query" or "header" param
	//
	// Defaults to "query"
	In string
	// Example is the OAS example for the param
	Example any
	// Schema is the optional OAS Schema
	Schema *Schema
	// SchemaRef is the OAS schema reference
	//
	// Only used if value is a non-empty string - if both Schema is nil and SchemaRef is empty string, then an
	// empty object schema is written to the spec yaml, e.g.
	//   schema:
	//     type: "string"
	//
	// If the value does not contain a path (i.e. does not contain any "/") then the ref
	// path will be the value prefixed with components schemas path.  For example, specifying "foo"
	// will result in a schema ref:
	//   schema:
	//     $ref: "#/components/schemas/foo"
	SchemaRef string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml (not used with Ref)
	Comment string
	// Ref is the OAS $ref name for the parameter
	//
	// If this is a non-empty string, then a $ref to "#/components/parameters/" is used
	Ref string
}

QueryParam represents the OAS definition of a query param (or header param)

type QueryParams

type QueryParams []QueryParam

QueryParams represents an ordered collection of QueryParam

type RapidocOptions added in v1.15.0

type RapidocOptions struct {
	ShowHeader             bool   // show-header
	HeadingText            string // heading-text
	Theme                  string // theme="light"
	RenderStyle            string // render-style="view"
	SchemaStyle            string // schema-style="table"
	ShowMethodInNavBar     string // show-method-in-nav-bar="true"
	UsePathInNavBar        bool   // use-path-in-nav-bar="true"
	ShowComponents         bool   // show-components="true"
	HideInfo               bool   // !show-info="true"
	AllowSearch            bool   // allow-search="false"
	AllowAdvancedSearch    bool   // allow-advanced-search="false"
	AllowSpecUrlLoad       bool   // allow-spec-url-load="false"
	AllowSpecFileLoad      bool   // allow-spec-file-load="false"
	DisallowTry            bool   // !allow-try="true"
	DisallowSpecDownload   bool   // !allow-spec-file-download="true"
	AllowServerSelection   bool   // allow-server-selection="false"
	DisallowAuthentication bool   // !allow-authentication="true"
	NoPersistAuth          bool   // !persist-auth="true"
	UpdateRoute            bool   // update-route="true"
	MatchType              string // match-type="regex"
	MonoFont               string // mono-font
	RegularFont            string // regular-font
	HeaderColor            string // header-color
	PrimaryColor           string // primary-color
	SchemaExpandLevel      uint   // schema-expand-level
	// LogoSrc is the src for Rapidoc logo
	LogoSrc string
	// InnerHtml is any inner HTML for the <rapi-doc> element
	InnerHtml  template.HTML
	HeadScript template.JS
	BodyScript template.JS
	FavIcons   FavIcons
	// AdditionalAttributes is used to add any rapidoc attributes
	// not covered by other options
	//
	// Full reference at https://rapidocweb.com/api.html#att
	AdditionalAttributes map[string]string
}

RapidocOptions describes the rapidoc-ui options

for documentation see https://github.com/rapi-doc/RapiDoc

func (RapidocOptions) GetFavIcons added in v1.16.1

func (o RapidocOptions) GetFavIcons() FavIcons

func (RapidocOptions) ToMap added in v1.15.0

func (o RapidocOptions) ToMap() map[string]any

type RedocArrow added in v1.1.1

type RedocArrow struct {
	Size  string `json:"size,omitempty"`  // '1.5em'
	Color string `json:"color,omitempty"` // COMPUTED: theme.sidebar.textColor
}

func (*RedocArrow) ToMap added in v1.9.0

func (o *RedocArrow) ToMap() map[string]any

type RedocBreakpoints added in v1.1.1

type RedocBreakpoints struct {
	Small  string `json:"small,omitempty"`  // '50rem'
	Medium string `json:"medium,omitempty"` // '85rem'
	Large  string `json:"large,omitempty"`  // '105rem'
}

RedocBreakpoints breakpoints for switching three/two and mobile view layouts

func (*RedocBreakpoints) ToMap added in v1.9.0

func (o *RedocBreakpoints) ToMap() map[string]any

type RedocCode added in v1.1.1

type RedocCode struct {
	FontSize        string `json:"fontSize,omitempty"`        // '13px'
	FontFamily      string `json:"fontFamily,omitempty"`      // 'Courier, monospace'
	LineHeight      string `json:"lineHeight,omitempty"`      // COMPUTED: typography.lineHeight
	FontWeight      string `json:"fontWeight,omitempty"`      // COMPUTED: typography.fontWeightRegular
	Color           string `json:"color,omitempty"`           // '#e53935'
	BackgroundColor string `json:"backgroundColor,omitempty"` // 'rgba(38, 50, 56, 0.05)'
	Wrap            bool   `json:"wrap,omitempty"`            // whether to break word for inline blocks (otherwise they can overflow)
}

func (*RedocCode) ToMap added in v1.9.0

func (o *RedocCode) ToMap() map[string]any

type RedocColors added in v1.1.1

type RedocColors struct {
	TonalOffset float32 `json:"tonalOffset,omitempty"` // 0.3 # default tonal offset used in computations
}

func (*RedocColors) ToMap added in v1.9.0

func (o *RedocColors) ToMap() map[string]any

type RedocFab added in v1.1.1

type RedocFab struct {
	BackgroundColor string `json:"backgroundColor,omitempty"` // '#263238'
	Color           string `json:"color,omitempty"`           // '#ffffff'
}

func (*RedocFab) ToMap added in v1.9.0

func (o *RedocFab) ToMap() map[string]any

type RedocGroupItems added in v1.1.1

type RedocGroupItems struct {
	ActiveBackgroundColor string `json:"activeBackgroundColor,omitempty"` // COMPUTED: theme.sidebar.backgroundColor
	ActiveTextColor       string `json:"activeTextColor,omitempty"`       // COMPUTED: theme.sidebar.activeTextColor
	TextTransform         string `json:"textTransform,omitempty"`         // 'uppercase'
}

func (*RedocGroupItems) ToMap added in v1.9.0

func (o *RedocGroupItems) ToMap() map[string]any

type RedocHeadings added in v1.1.1

type RedocHeadings struct {
	FontFamily string `json:"fontFamily,omitempty"` // 'Montserrat, sans-serif'
	FontWeight string `json:"fontWeight,omitempty"` // '400'
	LineHeight string `json:"lineHeight,omitempty"` // '1.6em'
}

func (*RedocHeadings) ToMap added in v1.9.0

func (o *RedocHeadings) ToMap() map[string]any

type RedocLevel1Items added in v1.1.1

type RedocLevel1Items struct {
	ActiveBackgroundColor string `json:"activeBackgroundColor,omitempty"` // COMPUTED: theme.sidebar.backgroundColor
	ActiveTextColor       string `json:"activeTextColor,omitempty"`       // COMPUTED: theme.sidebar.activeTextColor
	TextTransform         string `json:"textTransform,omitempty"`         // 'none'
}

func (*RedocLevel1Items) ToMap added in v1.9.0

func (o *RedocLevel1Items) ToMap() map[string]any
type RedocLinks struct {
	Color               string `json:"color,omitempty"`               // COMPUTED: colors.primary.main
	Visited             string `json:"visited,omitempty"`             // COMPUTED: typography.links.color
	Hover               string `json:"hover,omitempty"`               // COMPUTED: lighten(0.2 typography.links.color)
	TextDecoration      string `json:"textDecoration,omitempty"`      // 'auto'
	HoverTextDecoration string `json:"hoverTextDecoration,omitempty"` // 'auto'
}

func (*RedocLinks) ToMap added in v1.9.0

func (o *RedocLinks) ToMap() map[string]any
type RedocLogo struct {
	MaxHeight int    `json:"maxHeight,omitempty"` // COMPUTED: sidebar.width
	MaxWidth  int    `json:"maxWidth,omitempty"`  // COMPUTED: sidebar.width
	Gutter    string `json:"gutter,omitempty"`    // '2px' # logo image padding
}

func (*RedocLogo) ToMap added in v1.9.0

func (o *RedocLogo) ToMap() map[string]any

type RedocOptions added in v1.1.1

type RedocOptions struct {
	DisableSearch                   bool          `json:"disableSearch,omitempty"`                   // disable search indexing and search box.
	MinCharacterLengthToInitSearch  int           `json:"minCharacterLengthToInitSearch,omitempty"`  // set minimal characters length to init search, default 3, minimal 1.
	ExpandDefaultServerVariables    bool          `json:"expandDefaultServerVariables,omitempty"`    // enable expanding default server variables, default false.
	ExpandResponses                 string        `json:"expandResponses,omitempty"`                 // specify which responses to expand by default by response codes. Values should be passed as comma-separated list without spaces e.g. expandResponses="200,201". Special value "all" expands all responses by default. Be careful: this option can slow-down documentation rendering time.
	GeneratedPayloadSamplesMaxDepth int           `json:"generatedPayloadSamplesMaxDepth,omitempty"` // set the maximum render depth for JSON payload samples (responses and request body). The default value is 10.
	MaxDisplayedEnumValues          int           `json:"maxDisplayedEnumValues,omitempty"`          // display only specified number of enum values. hide rest values under spoiler.
	HideDownloadButton              bool          `json:"hideDownloadButton,omitempty"`              // do not show "Download" spec button. THIS DOESN'T MAKE YOUR SPEC PRIVATE, it just hides the button.
	DownloadFileName                string        `json:"downloadFileName,omitempty"`                // set a custom file name for the downloaded API definition file.
	DownloadDefinitionUrl           string        `json:"downloadDefinitionUrl,omitempty"`           // If the 'Download' button is visible in the API reference documentation (hideDownloadButton=false), the URL configured here opens when that button is selected. Provide it as an absolute URL with the full URI scheme.
	HideHostname                    bool          `json:"hideHostname,omitempty"`                    // if set, the protocol and hostname is not shown in the operation definition.
	HideLoading                     bool          `json:"hideLoading,omitempty"`                     // do not show loading animation. Useful for small docs.
	HideFab                         bool          `json:"hideFab,omitempty"`                         // do not show FAB in mobile view. Useful for implementing a custom floating action button.
	HideSchemaPattern               bool          `json:"hideSchemaPattern,omitempty"`               // if set, the pattern is not shown in the schema.
	HideSingleRequestSampleTab      bool          `json:"hideSingleRequestSampleTab,omitempty"`      // do not show the request sample tab for requests with only one sample.
	ShowObjectSchemaExamples        bool          `json:"showObjectSchemaExamples,omitempty"`        // show object schema example in the properties, default false.
	ExpandSingleSchemaField         bool          `json:"expandSingleSchemaField,omitempty"`         // automatically expand single field in a schema
	SchemaExpansionLevel            any           `json:"schemaExpansionLevel,omitempty"`            // specifies whether to automatically expand schemas. Special value "all" expands all levels. The default value is 0.
	JsonSampleExpandLevel           any           `json:"jsonSampleExpandLevel,omitempty"`           // set the default expand level for JSON payload samples (responses and request body). Special value "all" expands all levels. The default value is 2.
	HideSchemaTitles                bool          `json:"hideSchemaTitles,omitempty"`                // do not display schema title next to the type
	SimpleOneOfTypeLabel            bool          `json:"simpleOneOfTypeLabel,omitempty"`            // show only unique oneOf types in the label without titles
	SortEnumValuesAlphabetically    bool          `json:"sortEnumValuesAlphabetically,omitempty"`    // set to true, sorts all enum values in all schemas alphabetically
	SortOperationsAlphabetically    bool          `json:"sortOperationsAlphabetically,omitempty"`    // set to true, sorts operations in the navigation sidebar and in the middle panel alphabetically
	SortTagsAlphabetically          bool          `json:"sortTagsAlphabetically,omitempty"`          // set to true, sorts tags in the navigation sidebar and in the middle panel alphabetically
	MenuToggle                      bool          `json:"menuToggle,omitempty"`                      // if true, clicking second time on expanded menu item collapses it, default true.
	NativeScrollbars                bool          `json:"nativeScrollbars,omitempty"`                // use native scrollbar for sidemenu instead of perfect-scroll (scrolling performance optimization for big specs).
	OnlyRequiredInSamples           bool          `json:"onlyRequiredInSamples,omitempty"`           // shows only required fields in request samples.
	PathInMiddlePanel               bool          `json:"pathInMiddlePanel,omitempty"`               // show path link and HTTP verb in the middle panel instead of the right one.
	RequiredPropsFirst              bool          `json:"requiredPropsFirst,omitempty"`              // show required properties first ordered in the same order as in required array.
	ScrollYOffset                   any           `json:"scrollYOffset,omitempty"`                   // If set, specifies a vertical scroll-offset. This is often useful when there are fixed positioned elements at the top of the page, such as navbars, headers etc; scrollYOffset can be specified in various ways:
	ShowExtensions                  bool          `json:"showExtensions,omitempty"`                  // show vendor extensions ("x-" fields). Extensions used by Redoc are ignored. Can be boolean or an array of string with names of extensions to display.
	SortPropsAlphabetically         bool          `json:"sortPropsAlphabetically,omitempty"`         // sort properties alphabetically.
	PayloadSampleIndex              int           `json:"payloadSampleIdx,omitempty"`                // if set, payload sample is inserted at this index or last. Indexes start from 0.
	Theme                           *RedocTheme   `json:"theme,omitempty"`                           // Redoc theme
	UntrustedSpec                   bool          `json:"untrustedSpec,omitempty"`                   // if set, the spec is considered untrusted and all HTML/markdown is sanitized to prevent XSS. Disabled by default for performance reasons. Enable this option if you work with untrusted user data!
	Nonce                           any           `json:"nonce,omitempty"`                           // if set, the provided value is injected in every injected HTML element in the nonce attribute. Useful when using CSP, see https://webpack.js.org/guides/csp/.
	SideNavStyle                    string        `json:"sideNavStyle,omitempty"`                    // can be specified in various ways: "summary-only" (default), "path-only" or id-only"
	ShowWebhookVerb                 bool          `json:"showWebhookVerb,omitempty"`                 // when set to true, shows the HTTP request method for webhooks in operations and in the sidebar.
	FavIcons                        FavIcons      `json:"-"`
	HeaderHtml                      template.HTML `json:"-"`
	HeadScript                      template.JS   `json:"-"`
	BodyScript                      template.JS   `json:"-"`
}

RedocOptions for use in DocOptions.RedocOptions (from https://github.com/Redocly/redoc#redoc-options-object)

func (RedocOptions) GetFavIcons added in v1.16.1

func (o RedocOptions) GetFavIcons() FavIcons

func (RedocOptions) ToMap added in v1.9.0

func (o RedocOptions) ToMap() map[string]any

type RedocRightPanel added in v1.1.1

type RedocRightPanel struct {
	BackgroundColor string                  `json:"backgroundColor,omitempty"` // '#263238'
	Width           string                  `json:"width,omitempty"`           // '40%'
	TextColor       string                  `json:"textColor,omitempty"`       // '#ffffff'
	Servers         *RedocRightPanelServers `json:"servers,omitempty"`
}

func (*RedocRightPanel) ToMap added in v1.9.0

func (o *RedocRightPanel) ToMap() map[string]any

type RedocRightPanelServers added in v1.1.5

type RedocRightPanelServers struct {
	Overlay *RedocRightPanelServersOverlay `json:"overlay,omitempty"`
	Url     *RedocRightPanelServersUrl     `json:"url,omitempty"`
}

func (*RedocRightPanelServers) ToMap added in v1.9.0

func (o *RedocRightPanelServers) ToMap() map[string]any

type RedocRightPanelServersOverlay added in v1.1.5

type RedocRightPanelServersOverlay struct {
	BackgroundColor string `json:"backgroundColor,omitempty"` // '#fafafa'
	TextColor       string `json:"textColor,omitempty"`       // '#263238'
}

func (*RedocRightPanelServersOverlay) ToMap added in v1.9.0

func (o *RedocRightPanelServersOverlay) ToMap() map[string]any

type RedocRightPanelServersUrl added in v1.1.5

type RedocRightPanelServersUrl struct {
	BackgroundColor string `json:"backgroundColor,omitempty"` // '#fff'
}

func (*RedocRightPanelServersUrl) ToMap added in v1.9.0

func (o *RedocRightPanelServersUrl) ToMap() map[string]any

type RedocSidebar added in v1.1.1

type RedocSidebar struct {
	Width           string            `json:"width,omitempty"`           // '260px'
	BackgroundColor string            `json:"backgroundColor,omitempty"` // '#fafafa'
	TextColor       string            `json:"textColor,omitempty"`       // '#333333'
	ActiveTextColor string            `json:"activeTextColor,omitempty"` // COMPUTED: theme.sidebar.textColor (if set by user) or theme.colors.primary.main
	GroupItems      *RedocGroupItems  `json:"groupItems,omitempty"`      // Group headings
	Level1Items     *RedocLevel1Items `json:"level1Items,omitempty"`     //  Level 1 items like tags or section 1st level items
	Arrow           *RedocArrow       `json:"arrow,omitempty"`           // sidebar arrow
}

func (*RedocSidebar) ToMap added in v1.9.0

func (o *RedocSidebar) ToMap() map[string]any

type RedocSpacing added in v1.1.1

type RedocSpacing struct {
	Unit              int `json:"unit,omitempty"`              // 5 # main spacing unit used in autocomputed theme values later
	SectionHorizontal int `json:"sectionHorizontal,omitempty"` // 40 # Horizontal section padding. COMPUTED: spacing.unit * 8
	SectionVertical   int `json:"sectionVertical,omitempty"`   // 40 # Horizontal section padding. COMPUTED: spacing.unit * 8
}

func (*RedocSpacing) ToMap added in v1.9.0

func (o *RedocSpacing) ToMap() map[string]any

type RedocTheme added in v1.1.1

type RedocTheme struct {
	Spacing     *RedocSpacing     `json:"spacing,omitempty"`
	Breakpoints *RedocBreakpoints `json:"breakpoints,omitempty"`
	Colors      *RedocColors      `json:"colors,omitempty"`
	Typography  *RedocTypography  `json:"typography,omitempty"`
	Sidebar     *RedocSidebar     `json:"sidebar,omitempty"`
	RightPanel  *RedocRightPanel  `json:"rightPanel,omitempty"`
	Fab         *RedocFab         `json:"fab,omitempty"`
}

func (*RedocTheme) ToMap added in v1.9.0

func (o *RedocTheme) ToMap() map[string]any

type RedocTypography added in v1.1.1

type RedocTypography struct {
	FontSize          string         `json:"fontSize,omitempty"`          // '14px'
	LineHeight        string         `json:"lineHeight,omitempty"`        // '1.5em'
	FontWeightRegular string         `json:"fontWeightRegular,omitempty"` // '400'
	FontWeightBold    string         `json:"fontWeightBold,omitempty"`    // '600'
	FontWeightLight   string         `json:"fontWeightLight,omitempty"`   // '300'
	FontFamily        string         `json:"fontFamily,omitempty"`        // 'Roboto, sans-serif'
	Smoothing         string         `json:"smoothing,omitempty"`         // 'antialiased'
	OptimizeSpeed     bool           `json:"optimizeSpeed"`               // true
	Headings          *RedocHeadings `json:"headings,omitempty"`
	Code              *RedocCode     `json:"code,omitempty"`
	Links             *RedocLinks    `json:"links,omitempty"`
}

func (RedocTypography) ToMap added in v1.9.0

func (o RedocTypography) ToMap() map[string]any

type Request

type Request struct {
	// Ref is the OAS $ref name for the request
	//
	// If this is a non-empty string and the response is used by Method.Request, then a $ref to "#/components/requestBodies/" is used
	//
	// If the Request is used by Components.Requests this value is ignored
	Ref string
	// Description is the OAS description
	Description string
	// Required is the OAS flag determining if the request is required
	Required bool
	// ContentType is the OAS content type
	//
	// defaults to "application/json"
	ContentType string
	// AlternativeContentTypes is a map of alternative content types (where the key is the media type - e.g. "application/json")
	AlternativeContentTypes ContentTypes
	// Schema is the optional OAS Schema
	//
	// Only used if the value is non-nil - otherwise uses SchemaRef is used
	//
	// The value can be any of the following:
	//
	// * chioas.Schema (or *chioas.Schema)
	//
	// * a chioas.SchemaConverter
	//
	// * a chioas.SchemaWriter
	//
	// * a struct or ptr to struct (schema written is determined by examining struct fields)
	//
	// * a slice of structs (items schema written is determined by examining struct fields)
	Schema any
	// SchemaRef is the OAS schema reference
	//
	// Only used if value is a non-empty string - if both Schema is nil and SchemaRef is empty string, then an
	// empty object schema is written to the spec yaml, e.g.
	//   schema:
	//     type: "object"
	//
	// If the value does not contain a path (i.e. does not contain any "/") then the ref
	// path will be the value prefixed with components schemas path.  For example, specifying "foo"
	// will result in a schema ref:
	//   schema:
	//     $ref: "#/components/schemas/foo"
	SchemaRef string
	// IsArray indicates that request is an array of items
	IsArray bool
	// Examples is the ordered list of examples for the request
	Examples Examples
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml (not used with Ref)
	Comment string
}

Request represents the OAS definition of a request

type Response

type Response struct {
	// Ref is the OAS $ref name for the response
	//
	// If this is a non-empty string and the response is used by Method.Responses, then a $ref to "#/components/responses/" is used
	//
	// If the Response is used by Components.ResponseBodies this value is ignored
	Ref string
	// Description is the OAS description
	Description string
	// NoContent indicates that this response has not content
	//
	// This does not eed to set this when status code is http.StatusNoContent
	NoContent bool
	// ContentType is the OAS content type
	//
	// defaults to "application/json"
	ContentType string
	// AlternativeContentTypes is a map of alternative content types (where the key is the media type - e.g. "application/json")
	AlternativeContentTypes ContentTypes
	// Schema is the optional OAS Schema
	//
	// Only used if the value is non-nil - otherwise uses SchemaRef is used
	//
	// The value can be any of the following:
	//
	// * chioas.Schema (or *chioas.Schema)
	//
	// * a chioas.SchemaConverter
	//
	// * a chioas.SchemaWriter
	//
	// * a struct or ptr to struct (schema written is determined by examining struct fields)
	//
	// * a slice of structs (items schema written is determined by examining struct fields)
	Schema any
	// SchemaRef is the OAS schema reference
	//
	// Only used if value is a non-empty string - if both Schema is nil and SchemaRef is empty string, then an
	// empty object schema is written to the spec yaml, e.g.
	//   schema:
	//     type: "object"
	//
	// If the value does not contain a path (i.e. does not contain any "/") then the ref
	// path will be the value prefixed with components schemas path.  For example, specifying "foo"
	// will result in a schema ref:
	//   schema:
	//     $ref: "#/components/schemas/foo"
	SchemaRef string
	// IsArray indicates that request is an array of items
	IsArray bool
	// Examples is the ordered list of examples for the response
	Examples Examples
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml (not used with Ref)
	Comment string
}

Response is the OAS definition of a response

type Responses

type Responses map[int]Response

Responses is a map of Response where the key is the http status code

type Schema

type Schema struct {
	// Name is the OAS name of the schema
	Name string
	// Description is the OAS description
	Description string
	// Type is the OAS type
	//
	// Should be one of "string", "object", "array", "boolean", "integer", "number" or "null"
	Type string
	// Format is the OAS format
	Format string
	// RequiredProperties is the ordered collection of required properties
	//
	// If any of the items in Properties is also denoted as Property.Required, these are
	// automatically added to RequiredProperties
	RequiredProperties []string
	// Properties is the ordered collection of properties
	Properties Properties
	// Default is the OAS default
	Default any
	// Example is the OAS example for the schema
	Example any
	// Enum is the OAS enum
	Enum []any
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
	// SchemaRef is the OAS schema reference
	//
	// Only used if value is a non-empty string
	//
	// If the value does not contain a path (i.e. does not contain any "/") then the ref
	// path will be the value prefixed with components schemas path.  For example, specifying "foo"
	// will result in a schema ref:
	//   schema:
	//     $ref: "#/components/schemas/foo"
	SchemaRef string
	// Discriminator is the optional OAS discriminator for the schema
	Discriminator *Discriminator
	// Ofs is the optional OAS ofs (oneOf, anyOf or allOf) for the schema
	Ofs *Ofs
}

Schema represents the OAS definition of a schema

func (*Schema) From added in v1.10.0

func (s *Schema) From(sample any) (*Schema, error)

From generates a schema from the provided sample

where the sample must be a struct or pointer to struct

example:

type MyRequest struct {
	GivenName    string   `json:"givenName" oas:"description:'Your first/given name',required,pattern:'^[A-Z][a-zA-Z]+$',example"`
	FamilyName   string   `json:"familyName" oas:"description:'Your family name/surname',required,pattern:'^[A-Z][a-zA-Z]+$',example"`
	Age          int      `oas:"name:age,required:true,example,#this is a comment,#'this is another, with commas in it, comment'"`
	SiblingNames []string `oas:"name:siblings,$ref:'Siblings'"`
}
def := chioas.Definition{
	Components: &chioas.Components{
		Schemas: chioas.Schemas{
			(&Schema{
				Name:        "MyRequest",
				Description: "My request",
			}).Must(MyRequest{
				GivenName:  "Bilbo",
				FamilyName: "Baggins",
				Age:        50,
			}),
		},
	},
}
data, _ := def.AsYaml()
println(string(data))

would produce the following OAS spec yaml:

openapi: "3.0.3"
info:
  title: "API Documentation"
  version: "1.0.0"
paths:
components:
  schemas:
    "MyRequest":
      description: "My request"
      type: "object"
      required:
        - "givenName"
        - "familyName"
        - "age"
      properties:
        "givenName":
          description: "Your first/given name"
          type: "string"
          example: "Bilbo"
          pattern: "^[A-Z][a-zA-Z]+$"
        "familyName":
          description: "Your family name/surname"
          type: "string"
          example: "Baggins"
          pattern: "^[A-Z][a-zA-Z]+$"
        "age":
          #this is a comment
          #this is another, with commas in it, comment
          type: "integer"
          example: 50
        "siblings":
          type: "array"
          items:
            $ref: "#/components/schemas/Siblings"

In the field tags, the following OAS tokens can be used:

$ref:string (sets the SchemaRef)
deprecated:true|false
deprecated (same as deprecated:true)
description:string
enum:any (adds an enum value to the property)
enum:[any,any,...] (adds multiple enum values to the property)
example (sets the Property.Example from the provided sample - if available)
exclusiveMaximum:true|false
exclusiveMaximum (same as exclusiveMaximum:true)
exclusiveMinimum:true|false
exclusiveMinimum (same as exclusiveMinimum:true)
format:string
itemType:""|"string"|"object"|"array"|"boolean"|"integer"|"number"|"null"
maxItems:uint
maxLength:uint
maxProperties:uint
maximum:number
minItems:uint
minLength:uint
minProperties:uint
minimum:number
multipleOf:uint
name:string
nullable:true|false
nullable (same as nullable:true)
pattern:string
required:true|false
required (same as required:true)
type:""|"string"|"object"|"array"|"boolean"|"integer"|"number"|"null"
uniqueItems:true|false
uniqueItems (same as uniqueItems:true)
x-...:string (sets an OAS extension property)
#comment (adds a comment to the property)

func (*Schema) IsRef added in v1.11.0

func (s *Schema) IsRef() bool

func (*Schema) Must added in v1.10.0

func (s *Schema) Must(sample any) Schema

Must is the same as MustFrom except it panics on error or returns non-pointer Schema

func (*Schema) MustFrom added in v1.10.0

func (s *Schema) MustFrom(sample any) *Schema

MustFrom is the same as From except it panics on error

func (*Schema) Ref added in v1.11.0

func (s *Schema) Ref() string

func (*Schema) Schema added in v1.11.0

func (s *Schema) Schema() *Schema

type SchemaConverter added in v1.4.0

type SchemaConverter interface {
	ToSchema() *Schema
}

SchemaConverter is an interface that can be implemented by anything to convert it to a schema

type SchemaWriter added in v1.4.0

type SchemaWriter interface {
	WriteSchema(w yaml.Writer)
}

SchemaWriter is an interface that can be implemented by anything to write a schema for that item

type Schemas

type Schemas []Schema

type SecurityScheme added in v1.2.0

type SecurityScheme struct {
	// Name is the OAS name of the security scheme
	Name string
	// Description is the OAS description
	Description string
	// Type is the OAS security scheme type
	//
	// Valid values are: "apiKey", "http", "mutualTLS", "oauth2", "openIdConnect"
	//
	// Defaults to "http"
	Type string
	// Scheme is the OAS HTTP Authorization scheme
	Scheme string
	// ParamName is the OAS param name (in query, header or cookie)
	ParamName string
	// In is the OAS definition of where the API key param is found
	//
	// Valid values are: "query", "header" or "cookie"
	In string
	// Scopes is the security requirement scopes
	//
	// Only used when the SecurityScheme is part of Definition.Security and the
	// Type is either "oauth2" or "openIdConnect"
	Scopes []string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

SecurityScheme represents the OAS definition of a security scheme

type SecuritySchemes added in v1.2.0

type SecuritySchemes []SecurityScheme

SecuritySchemes is an ordered collection of SecurityScheme

Used by:

* Components.SecuritySchemes to define the security schemes used by the api

* Definition.Security to define the security requirements across the entire api

* Method.Security to define the security requirement for a particular method

type Server

type Server struct {
	// Description is the OAS description
	Description string
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

Server represents the OAS definition of a server

type Servers

type Servers map[string]Server

type SupportFiles added in v1.8.1

type SupportFiles interface {
	ServeHTTP(http.ResponseWriter, *http.Request)
}

type SwaggerOptions added in v1.9.0

type SwaggerOptions struct {
	DomId                    string          `json:"dom_id,omitempty"`
	Layout                   string          `json:"layout,omitempty"`
	DeepLinking              bool            `json:"deepLinking"`
	DisplayOperationId       bool            `json:"displayOperationId"`
	DefaultModelsExpandDepth uint            `json:"defaultModelsExpandDepth,omitempty"`
	DefaultModelExpandDepth  uint            `json:"defaultModelExpandDepth,omitempty"`
	DefaultModelRendering    string          `json:"defaultModelRendering,omitempty"`
	DisplayRequestDuration   bool            `json:"displayRequestDuration"`
	DocExpansion             string          `json:"docExpansion,omitempty"`
	MaxDisplayedTags         uint            `json:"maxDisplayedTags,omitempty"`
	ShowExtensions           bool            `json:"showExtensions"`
	ShowCommonExtensions     bool            `json:"showCommonExtensions"`
	UseUnsafeMarkdown        bool            `json:"useUnsafeMarkdown"`
	SyntaxHighlightTheme     string          `json:"syntaxHighlight.theme,omitempty"`
	TryItOutEnabled          bool            `json:"tryItOutEnabled"`
	RequestSnippetsEnabled   bool            `json:"requestSnippetsEnabled"`
	SupportedSubmitMethods   []string        `json:"supportedSubmitMethods,omitempty"`
	ValidatorUrl             string          `json:"validatorUrl,omitempty"`
	WithCredentials          bool            `json:"withCredentials"`
	PersistAuthorization     bool            `json:"persistAuthorization"`
	Plugins                  []SwaggerPlugin `json:"-"`
	Presets                  []SwaggerPreset `json:"-"`
	FavIcons                 FavIcons        `json:"-"`
	HeaderHtml               template.HTML   `json:"-"`
	HeadScript               template.JS     `json:"-"`
	BodyScript               template.JS     `json:"-"`
}

SwaggerOptions describes the swagger-ui options (as used by DocOptions.SwaggerOptions)

for documentation see https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md

func (SwaggerOptions) GetFavIcons added in v1.16.1

func (o SwaggerOptions) GetFavIcons() FavIcons

func (SwaggerOptions) ToMap added in v1.9.0

func (o SwaggerOptions) ToMap() map[string]any

type SwaggerPlugin added in v1.9.0

type SwaggerPlugin string

SwaggerPlugin is used by SwaggerOptions.Plugins

type SwaggerPreset added in v1.9.0

type SwaggerPreset string

SwaggerPreset is used by SwaggerOptions.Presets

type Tag

type Tag struct {
	// Name is the OAS name of the tag
	Name string
	// Description is the OAS description
	Description string
	// ExternalDocs is the optional OAS external docs
	ExternalDocs *ExternalDocs
	// Extensions is extension OAS yaml properties
	Extensions Extensions
	// Additional is any additional OAS spec yaml to be written
	Additional Additional
	// Comment is any comment(s) to appear in the OAS spec yaml
	Comment string
}

Tag represents the OAS definition of a tag

type Tags

type Tags []Tag

Tags is an ordered collection of Tag

type UIStyle added in v1.9.0

type UIStyle uint
const (
	Redoc   UIStyle = iota // style for Redoc UI
	Swagger                // style for swagger-ui
	Rapidoc                // style for rapidoc-ui
)

Directories

Path Synopsis
_examples
Package typed provides for the capability of having typed handlers (methods/functions) for api endpoints
Package typed provides for the capability of having typed handlers (methods/functions) for api endpoints

Jump to

Keyboard shortcuts

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