api

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2024 License: GPL-3.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FormatRegex map[string]*regexp.Regexp = map[string]*regexp.Regexp{
	"date-time":    regexp.MustCompile(`\d{4}-\d\d?-\d\d?[T ]\d\d?:\d\d:\d\d(\+\d\d:\d\d|)`),
	"time":         regexp.MustCompile(`\d\d?:\d\d:\d\d(\+\d\d:\d\d|)`),
	"date":         regexp.MustCompile(`\d{4}-\d\d?-\d\d?`),
	"byte":         regexp.MustCompile(`^\d+$`),
	"duration":     regexp.MustCompile(`^P((\d+\.)?\d+[YMWD]$)?((\d+\.)?\d+Y$)?((\d+\.)?\d+M$)?((\d+\.)?\d+W$)?((\d+\.)?\d+D$)?(T((\d+\.)?\d+[HMS]$)((\d+\.)?\d+H$)?((\d+\.)?\d+M$)?((\d+\.)?\d+S$)?)?`),
	"email":        regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`),
	"idn-email":    regexp.MustCompile(`.+@.+\..+`),
	"hostname":     regexp.MustCompile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`),
	"idn-hostname": regexp.MustCompile(`^(?:[\p{L}\p{N}][\p{L}\p{N}-_]*.)+[\p{L}\p{N}]{2,}$`),
	"ipv4":         regexp.MustCompile(`^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$`),
	"ipv6":         regexp.MustCompile(`(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))`),
	"uuid":         regexp.MustCompile(`^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$`),

	"json-pointer": regexp.MustCompile(`(/(([^/~])|(~[01]))*)`),

	"float":  regexp.MustCompile(`^[-+]?\d*(\.\d+|\d+)([eE]\d+)?$`),
	"double": regexp.MustCompile(`^[-+]?\d*(\.\d+|\d+)([eE]\d+)?$`),
	"int32":  regexp.MustCompile(`^[-+]?\d+$`),
	"int64":  regexp.MustCompile(`^[-+]?\d+$`),
}
View Source
var KindToFormat = map[reflect.Kind]string{
	reflect.Float32: "float",
	reflect.Float64: "double",
	reflect.Int32:   "int32",
	reflect.Int64:   "int64",
}

A map from GO kind to format.

Functions

func AddSchema added in v0.3.2

func AddSchema[V any](build *Builder)

Adds a built schema of the given type to the builder.

func Any

func Any(val any) *any

A utility function for all the *any fields in the api types.

func ApplyOptions

func ApplyOptions(s *Schema, tag string)

Applies the key=value & flag options found in tag to the given schema. Example format of tag: "title=Hi,required". Full list of examples:

  • title=Example title which can have\, commas
  • desc=A description of the schema.
  • description=A description of the schema.
  • format=date
  • pattern=\d{1\,3}.\d{1\,3}.\d{1\,3}.\d{1\,3}
  • deprecated
  • required
  • nullable
  • null
  • readonly
  • writeonly
  • enum=A|B|C|A\,B\,C
  • minlength=1
  • maxlength=1
  • multipleof=2
  • maximum=1
  • max=1
  • minimum=1
  • min=1
  • minitems=1
  • maxitems=1
  • exclusivemaximum=true
  • exclusivemax=1
  • exclusiveminimum=false
  • exclusivemin=0
  • oneof=X|A|B
  • allof=X|A|B
  • anyof=X|A|B

func EscapePathPart

func EscapePathPart(s string) string

Escapes a value so it can be used in a reference path.

func GetDescription

func GetDescription(valueOrType any) string

Gets the description defined on the given type, or "" if the type does not implement HasDescription.

func GetEnums

func GetEnums(valueOrType any) []any

Gets the enum values defined on the given type, or nil if the type does not implement HasEnum.

func GetExample

func GetExample(valueOrType any) *any

Gets the JSON example defined on the given value or type or returns nil if the type does not implement HasExample.

func GetJSONOptions

func GetJSONOptions(field reflect.StructField) (property string, optional bool, skip bool)

Gets the json options from the given struct field.

func GetName

func GetName(valueOrType any) string

Gets the Name of the given type. If it implements HasName then that name is returned.

func GetNameQualified

func GetNameQualified(valueOrType any) string

Gets the name of a given type, including the package path.

func GetOperationUpdate

func GetOperationUpdate(fnOrType any, op *Operation) bool

Gets the operation on the function instance or type or returns nil if the type does not implement HasAPIOperation.

func GetSchemaType added in v0.3.4

func GetSchemaType(valueOrType any) reflect.Type

Gets reflect.Type of the given type or value. This accounts for if the type/value implements the HasSchemaType.

func GetType

func GetType(valueOrType any) reflect.Type

Given a value or type, return the type.

func IsNamedType

func IsNamedType(valueOrType any) bool

Returns whether the given type implements HasName.

func Merge

func Merge[T CanMerge[T]](base T, next T, additional ...T) T

Merges zero or more mergeable values into a single value, where later arguments have higher priority.

func MergeCanMerge

func MergeCanMerge[V CanMerge[V]](base *V, next *V) *V

Merges base and next which implement CanMerge. This handles potential nils.

func MergeMap

func MergeMap[K comparable, V any](base map[K]V, next map[K]V) map[K]V

Merges two maps. The value types can implement CanReplace and CanMerge and the merging process will respect those implementations when dealing with shared keys.

func MergeSlice

func MergeSlice[V any](base []V, next []V) []V

Merges the two slices together, base first foolowed by next.

func MergeSliceReplace

func MergeSliceReplace[V CanReplace[V]](base []V, next []V) []V

Merges the two slices together, avoiding duplicates based on the implementation of CanReplace.

func MergeSliceUnique

func MergeSliceUnique[V comparable](base []V, next []V) []V

Merges the two slices together, avoiding duplicate values.

func MergeValue

func MergeValue[V comparable](base V, next V) V

Merges base & next. If next is empty, base is returned. Otherwise next is returned.

func Ref

func Ref[V any](name string) V

Returns a reference to the given type with the given name. The type needs to implement HasReference.

func SetBaseSchema

func SetBaseSchema[V any](build *Builder, s *Schema)

Sets the base schema on the given builder with the defined generic type. A schema can be defined with starting values, when it's first built it will pull in the base schema. The base schema should be defined before any building is done.

func SetFullSchema

func SetFullSchema[V any](build *Builder, s *Schema)

Sets the full schema on the given builder with the defined generic type. A schema can be defined in its entirety and schema building won't try to detect it. The full schema should be defined before any building is done.

func SetName added in v0.3.3

func SetName[V any](build *Builder, name string)

Sets the name of the given type

Types

type BoolSchema

type BoolSchema struct {
	// Non-nil if bool should be used
	Bool *bool
	// Non-nil of schema should be used
	Schema *Schema
}

A helper type when a schema or a boolean can be given.

func SchemaForBool

func SchemaForBool(b bool) *BoolSchema

Returns a BoolSchema for bool

func SchemaForSchema

func SchemaForSchema(s *Schema) *BoolSchema

Returns a BoolSchema for Schema

func (BoolSchema) MarshalJSON

func (bs BoolSchema) MarshalJSON() ([]byte, error)

func (*BoolSchema) UnmarshalJSON

func (bs *BoolSchema) UnmarshalJSON(data []byte) error

type Builder

type Builder struct {
	// The base document that will be used when Build() is called.
	Document Document
	// If a field is nullable (pointer) should it be marked as optional? (not required)
	NullableIsOptional bool
	// If a field is optional (not required) should we accept null
	OptionalIsNullable bool
	// If a slice without omitempty can be nullable
	SliceIsNullable bool
	// If a map without omitempty can be nullable
	MapIsNullable bool
	// All collisions that occurred on the last Build().
	Collisions map[reflect.Type]*Schema
	// A schema can be defined with starting values, when it's first built it will
	// pull in the base schema. The base schema should be defined before any building is done.
	BaseSchema map[reflect.Type]*Schema
	// A schema can be defined in its entirety and schema building won't try to detect it.
	// The full schema should be defined before any building is done.
	FullSchema map[reflect.Type]*Schema
	// An override name for the given type.
	Names map[reflect.Type]string
	// contains filtered or unexported fields
}

Builds an OpenAPI document, creating schemas from types, and deals with named schema collisions.

func NewBuilder

func NewBuilder() *Builder

Creates a new empty builder.

func (*Builder) AddExample

func (build *Builder) AddExample(name string, ex *Example)

Adds a named example to the builder.

func (*Builder) AddHeader

func (build *Builder) AddHeader(name string, header *Header)

Adds a named header to the builder.

func (build *Builder) AddLink(name string, link *Link)

Adds a named link to the builder.

func (*Builder) AddParameter

func (build *Builder) AddParameter(name string, param *Parameter)

Adds a named parameter to the builder.

func (*Builder) AddPath

func (build *Builder) AddPath(url string, path *Path)

Adds a path to the builder. If it already exists it may break references that were created with Builder.RefPath()

func (*Builder) AddRequestBody

func (build *Builder) AddRequestBody(name string, body *RequestBody)

Adds a named request body to the builder.

func (*Builder) AddResponse

func (build *Builder) AddResponse(name string, response *Response)

Adds a named response to the builder.

func (*Builder) AddSchema

func (build *Builder) AddSchema(typ reflect.Type)

Adds a schema to the builder for the given type. This is equivalent to calling builder.GetSchema() without getting the schema.

func (*Builder) AddSchemaOf added in v0.3.2

func (build *Builder) AddSchemaOf(val any)

Adds a schema to the builder for the type of the given value. This is equivalent to calling builder.GetSchema() without getting the schema.

func (*Builder) AddSecurity

func (build *Builder) AddSecurity(name string, security *Security)

Adds a named security to the builder.

func (*Builder) AddTag

func (build *Builder) AddTag(tag Tag)

Adds a tag to the builder.

func (*Builder) Build

func (build *Builder) Build() Document

Builds the current document.

func (*Builder) BuildJSON

func (build *Builder) BuildJSON() []byte

Builds the document and returns it as JSON

func (*Builder) BuildSchema

func (build *Builder) BuildSchema(typ reflect.Type, addToDocument bool) *Schema

Builds a schema for the given type, and potentially adds it to the builder. This should not be called if the type has a named schema defined for it and addToDocument = true.

func (*Builder) GetExample

func (build *Builder) GetExample(name string) *Example

Gets a named example or returns nil if it doesn't exist.

func (*Builder) GetHeader

func (build *Builder) GetHeader(name string) *Header

Gets a named header or returns nil if it doesn't exist.

func (*Builder) GetInnerSchema

func (build *Builder) GetInnerSchema(s Schema) *Schema

Gets the inner schema of the given schema or returns nil if there is none. A schema has an inner schema if its a schema that refers to a named schema but that schema is nullable or has extra metadata added to the named schema.

func (build *Builder) GetLink(name string) *Link

Gets a named link or returns nil if it doesn't exist.

func (*Builder) GetParameter

func (build *Builder) GetParameter(name string) *Parameter

Gets a named parameter or returns nil if it doesn't exist.

func (*Builder) GetPath

func (build *Builder) GetPath(url string) *Path

Gets the path at the given URL.

func (*Builder) GetRequestBody

func (build *Builder) GetRequestBody(name string) *RequestBody

Gets a named request body or returns nil if it doesn't exist.

func (*Builder) GetResponse

func (build *Builder) GetResponse(name string) *Response

Gets a named response or returns nil if it doesn't exist.

func (*Builder) GetSchema

func (build *Builder) GetSchema(typ reflect.Type) *Schema

Gets or builds the schema for the given type. If a schema could not be determined, nil is returned.

func (*Builder) GetSchemaOf added in v0.3.2

func (build *Builder) GetSchemaOf(v any) *Schema

Gets or builds the schema for the given value. If a schema could not be determined, nil is returned.

func (*Builder) GetSecurity

func (build *Builder) GetSecurity(name string) *Security

Gets a named security or returns nil if it doesn't exist.

func (*Builder) IsNullable

func (build *Builder) IsNullable(s Schema) bool

Returns whether the given schema points to a nullable value.

func (*Builder) RefExample

func (build *Builder) RefExample(name string) *Example

Gets a reference to the example with the given name, or returns nil if none exists.

func (*Builder) RefHeader

func (build *Builder) RefHeader(name string) *Header

Gets a reference to the header with the given name, or returns nil if none exists.

func (build *Builder) RefLink(name string) *Link

Gets a reference to the link with the given name, or returns nil if none exists.

func (*Builder) RefParameter

func (build *Builder) RefParameter(name string) *Parameter

Gets a reference to the parameter with the given name, or returns nil if none exists.

func (*Builder) RefPath

func (build *Builder) RefPath(url string) *Path

Gets a reference to the path at the given URL, or returns nil if none exists.

func (*Builder) RefRequestBody

func (build *Builder) RefRequestBody(name string) *RequestBody

Gets a reference to the request body with the given name, or returns nil if none exists.

func (*Builder) RefResponse

func (build *Builder) RefResponse(name string) *Response

Gets a reference to the response with the given name, or returns nil if none exists.

func (*Builder) RefSecurity

func (build *Builder) RefSecurity(name string) *Security

Gets a reference to the security with the given name, or returns nil if none exists.

func (*Builder) SetBaseSchemaOf added in v0.3.2

func (build *Builder) SetBaseSchemaOf(v any, s *Schema)

Sets the full schema for the given type base on an a value.

func (*Builder) SetFullSchemaOf added in v0.3.2

func (build *Builder) SetFullSchemaOf(v any, s *Schema)

Sets the full schema for the given type base on an a value.

func (*Builder) SetName added in v0.3.3

func (build *Builder) SetName(typ reflect.Type, name string)

Sets the name of the type based on the value.

func (*Builder) SetNameOf added in v0.3.3

func (build *Builder) SetNameOf(val any, name string)

Sets the name of the type based on the value.

type Callbacks

type Callbacks map[string]map[string]Path

A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.

type CanMerge

type CanMerge[T any] interface {
	// Merging incorporates value into this and returns a new value. This or value are not modified.
	// If value has non-default single values it will overwrite those values in this in the returned value.
	Merge(value T) T
}

A type which can be merged with another type. Merging is about returning the defined values in the given value and the values in the current value. The given value takes priority. Slices and maps have different merging strategies based on the implementation and the interfaces the value types implement.

type CanReplace

type CanReplace[T any] interface {
	IsUnique(value T) bool
}

A mergeable type that can be uniquely identified

type Component

type Component struct {
	// An object to hold reusable Schema Objects.
	Schemas map[string]Schema `json:"schemas,omitempty"`
	// An object to hold reusable Response Objects.
	Responses Responses `json:"responses,omitempty"`
	// An object to hold reusable Parameter Objects.
	Parameters map[string]Parameter `json:"parameters,omitempty"`
	// An object to hold reusable Example Objects.
	Examples Examples `json:"examples,omitempty"`
	// An object to hold reusable Request Body Objects.
	RequestBodies map[string]RequestBody `json:"requestBodies,omitempty"`
	// An object to hold reusable Header Objects.
	Headers Headers `json:"headers,omitempty"`
	// An object to hold reusable Security Scheme Objects.
	SecuritySchemes map[string]Security `json:"securitySchemes,omitempty"`
	// An object to hold reusable Link Objects.
	Links Links `json:"links,omitempty"`
	// An object to hold reusable Callback Objects.
	Callbacks Callbacks `json:"callbacks,omitempty"`
}

Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. TODO PathItems

func (Component) Merge

func (base Component) Merge(next Component) Component

Merges components

type Contact

type Contact struct {
	// The identifying name of the contact person/organization.
	Name string `json:"name,omitempty"`
	// The URL pointing to the contact information. MUST be in the format of a URL.
	URL string `json:"url,omitempty"`
	// The email address of the contact person/organization. MUST be in the format of an email address.
	Email string `json:"email,omitempty"`
}

Contact information for the exposed API.

func (Contact) Merge

func (base Contact) Merge(next Contact) Contact

Merges contact

type ContentType

type ContentType string

Common content types that can be returned

const (
	ContentTypeJSON ContentType = "application/json"
	ContentTypeXML  ContentType = "application/xml"
	ContentTypeText ContentType = "text/plain"
	ContentTypeHTML ContentType = "text/html"
	ContentTypeAny  ContentType = "*/*"
	ContentTypeNone ContentType = ""
)

type Contents

type Contents map[ContentType]*MediaType

Helper type to make building content cleaner.

type DataType

type DataType string

Schema data types

const (
	DataTypeString  DataType = "string"
	DataTypeNumber  DataType = "number"
	DataTypeInteger DataType = "integer"
	DataTypeObject  DataType = "object"
	DataTypeArray   DataType = "array"
	DataTypeBoolean DataType = "boolean"
	DataTypeNull    DataType = "null"
)

type Discriminator

type Discriminator struct {
	// REQUIRED. The name of the property in the payload that will hold the discriminator value.
	PropertyName string `json:"propertyName"`
	// An object to hold mappings between payload values and schema names or references.
	Mapping map[string]string `json:"mapping"`
}

When request bodies or response payloads may be one of a number of different schemas, a discriminator object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it.

When using the discriminator, inline schemas will not be considered.

type Document

type Document struct {
	// REQUIRED. This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses. The openapi field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document. This is not related to the API info.version string.
	OpenAPI string `json:"openapi"`
	// REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.
	Info Info `json:"info"`
	// An array of Server Objects, which provide connectivity information to a target server. If the servers property is not provided, or is an empty array, the default value would be a Server Object with a url value of /.
	Servers []Server `json:"servers,omitempty"`
	// REQUIRED. The available paths and operations for the API.
	Paths map[string]Path `json:"paths"`
	// An element to hold various schemas for the specification.
	Components *Component `json:"components,omitempty"`
	// A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement ({}) can be included in the array.
	Security []Security `json:"security,omitempty"`
	// A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique.
	Tags []Tag `json:"tags,omitempty"`
	// Additional external documentation.
	ExternalDocs *ExternalDoc `json:"externalDocs,omitempty"`
}

This is the root document object of the OpenAPI document. TODO Webhooks

func (Document) Merge

func (base Document) Merge(next Document) Document

Merges documents

type Encoding

type Encoding struct {
	// The Content-Type for encoding a specific property. Default value depends on the property type: for string with format being binary – application/octet-stream; for other primitive types – text/plain; for object - application/json; for array – the default is defined based on the inner type. The value can be a specific media type (e.g. application/json), a wildcard media type (e.g. image/*), or a comma-separated list of the two types.
	ContentType string `json:"contentType,omitempty"`
	// A map allowing additional information to be provided as headers, for example Content-Disposition. Content-Type is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a multipart.
	Headers Headers `json:"headers,omitempty"`
	// Describes how a specific property value will be serialized depending on its type. See Parameter Object for details on the style property. The behavior follows the same values as query parameters, including default values. This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
	Style Style `json:"style,omitempty"`
	// When this is true, property values of type array or object generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When style is form, the default value is true. For all other styles, the default value is false. This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
	Explode bool `json:"explode,omitempty"`
	// Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding. The default value is false. This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
	AllowReserved bool `json:"allowReserved,omitempty"`
}

A single encoding definition applied to a single schema property.

type Encodings

type Encodings map[string]Encoding

Helper type to make building encodings cleaner.

type Example

type Example struct {
	// Allows for an external definition of this example.
	*Reference

	// Short description for the example.
	Summary string `json:"summary,omitempty"`
	// Long description for the example. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// Embedded literal example. The value field and externalValue field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary.
	Value *any `json:"value,omitempty"`
	// A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The value field and externalValue field are mutually exclusive.
	ExternalValue string `json:"externalValue,omitempty"`
	// contains filtered or unexported fields
}

func (Example) GetName

func (hr Example) GetName() *string

func (Example) GetReference

func (hr Example) GetReference() *Reference

func (Example) GetReferencePrefix

func (hr Example) GetReferencePrefix() string

func (*Example) SetReference

func (hr *Example) SetReference(ref string)

type Examples

type Examples map[string]Example

Helper type to make building examples cleaner.

func GetExamples

func GetExamples(valueOrType any, contentType ContentType) Examples

Gets the examples defined on the given type with the given contentType or returns nil if the type does not implement HasExamples.

type ExternalDoc

type ExternalDoc struct {
	// REQUIRED. The URL for the target documentation. Value MUST be in the format of a URL.
	URL string `json:"url"`
	// A short description of the target documentation. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
}

Allows referencing an external resource for extended documentation.

type HasBaseSchema

type HasBaseSchema interface {
	APIBaseSchema() *Schema
}

A type which can optionally provide schema defaults which can be built on with the default schema building behavior.

type HasDescription

type HasDescription interface {
	APIDescription() string
}

A type which has a specific description.

type HasEnum

type HasEnum interface {
	APIEnum() []any
}

A type which only accepts specific values. This values will be used in documentation and validation.

type HasExample

type HasExample interface {
	APIExample() *any
}

A type which has an example defined on it that will be used in the type's schema.

type HasExamples

type HasExamples interface {
	APIExamples(contentType ContentType) Examples
}

A type which has examples defined on it that will be used in the request, response, parameter, or header. If there are no examples for the requested contentType, return nil.

type HasFullSchema

type HasFullSchema interface {
	APIFullSchema() *Schema
}

A type which has its schema fully defined on it. This schema will be promoted to a named schema with exactly what is returned.

type HasName

type HasName interface {
	APIName() string
}

A type which has a specific name. Any type that implements this will be promoted to a named schema.

type HasOperation

type HasOperation interface {
	APIOperation() Operation
}

A function type can have an operation fully defined on it. The normal operation building logic will be skipped and this definition will be used. For operation augmentation see HasAPIOperationUpdate.

type HasOperationUpdate

type HasOperationUpdate interface {
	APIOperationUpdate(op *Operation)
}

A function type can alter the detected operation after its been built based on the functions argument types and return types.

type HasReference

type HasReference interface {
	GetReference() *Reference
	SetReference(ref string)
	GetReferencePrefix() string
}

A type which can have a reference, and can apply one.

type HasSchemaType added in v0.3.4

type HasSchemaType interface {
	APISchemaType() any
}

A type which has another type it actually marshals to and from. You can override the schema type by specifying a full or base schema but if the type is fundamentally different then the wrong validation and wrong examples can be generated.

type Header struct {
	// Allows for an external definition of this header.
	*Reference

	// Header shares the same fields
	ParameterBase
	// contains filtered or unexported fields
}

Similar to a parameter in the header, but reusable.

func (Header) GetReference

func (hr Header) GetReference() *Reference

func (Header) Merge

func (base Header) Merge(next Header) Header

Merges parameter

func (*Header) SetReference

func (hr *Header) SetReference(ref string)

type Headers

type Headers map[string]*Header

Helper type to make building headers cleaner.

type Info

type Info struct {
	// REQUIRED. The title of the API.
	Title string `json:"title"`
	// A short description of the API. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// A URL to the Terms of Service for the API. MUST be in the format of a URL.
	TermsOfService string `json:"termsOfService,omitempty"`
	// The contact information for the exposed API.
	Contact *Contact `json:"contact,omitempty"`
	// The license information for the exposed API.
	License *License `json:"license,omitempty"`
	// REQUIRED. The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).
	Version string `json:"version"`
}

The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. TODO Summary

func (Info) Merge

func (base Info) Merge(next Info) Info

Merges info

type License

type License struct {
	// REQUIRED. The license name used for the API.
	Name string `json:"name"`
	// A URL to the license used for the API. MUST be in the format of a URL.
	URL string `json:"url,omitempty"`
}

License information for the exposed API. TODO Identifier

func (License) Merge

func (base License) Merge(next License) License

Merges license

type Link struct {
	// Allows for an external definition of this link.
	*Reference

	// A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the operationId field, and MUST point to an Operation Object. Relative operationRef values MAY be used to locate an existing Operation Object in the OpenAPI definition.
	OperationRef string `json:"operationRef,omitempty"`
	// The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually exclusive of the operationRef field.
	OperationId string `json:"operationId,omitempty"`
	// A map representing parameters to pass to an operation as specified with operationId or identified via operationRef. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the parameter location [{in}.]{name} for operations that use the same parameter name in different locations (e.g. path.id).
	Parameters map[string]any `json:"parameters,omitempty"`
	// A literal value or {expression} to use as a request body when calling the target operation.
	RequestBody *any `json:"requestBody,omitempty"`
	// A description of the link. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// A server object to be used by the target operation.
	Server *Server `json:"server,omitempty"`
	// contains filtered or unexported fields
}

Using links, you can describe how various values returned by one operation can be used as input for other operations. This way, links provide a known relationship and traversal mechanism between the operations. The concept of links is somewhat similar to hypermedia, but OpenAPI links do not require the link information present in the actual responses.

func (Link) GetName

func (hr Link) GetName() *string

func (Link) GetReference

func (hr Link) GetReference() *Reference

func (Link) GetReferencePrefix

func (hr Link) GetReferencePrefix() string

func (*Link) SetReference

func (hr *Link) SetReference(ref string)
type Links map[string]Link

Helper type to make building links cleaner.

type MediaType

type MediaType struct {
	// The schema defining the content of the request, response, or parameter.
	Schema *Schema `json:"schema,omitempty"`
	// Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The example field is mutually exclusive of the examples field. Furthermore, if referencing a schema which contains an example, the example value SHALL override the example provided by the schema.
	Example *any `json:"example,omitempty"`
	// Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The examples field is mutually exclusive of the example field. Furthermore, if referencing a schema which contains an example, the examples value SHALL override the example provided by the schema.
	Examples Examples `json:"examples,omitempty"`
	// A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to requestBody objects when the media type is multipart or application/x-www-form-urlencoded.
	Encoding Encodings `json:"encoding,omitempty"`
}

Each Media Type Object provides schema and examples for the media type identified by its key.

type Operation

type Operation struct {
	// A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier.
	Tags []string `json:"tags,omitempty"`
	// A short summary of what the operation does.
	Summary string `json:"summary,omitempty"`
	// A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// Additional external documentation for this operation.
	ExternalDocs *ExternalDoc `json:"externalDocs,omitempty"`
	// Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions.
	OperationID string `json:"operationId,omitempty"`
	// A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.
	Parameters []Parameter `json:"parameters,omitempty"`
	// The request body applicable for this operation. The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers.
	RequestBody *RequestBody `json:"requestBody,omitempty"`
	// REQUIRED. The list of possible responses as they are returned from executing this operation.
	Responses Responses `json:"responses,omitempty"`
	// A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses.
	Callbacks Callbacks `json:"callbacks,omitempty"`
	// Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is false.
	Deprecated bool `json:"deprecated,omitempty"`
	// A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement ({}) can be included in the array. This definition overrides any declared top-level security. To remove a top-level security declaration, an empty array can be used.
	Security []SecurityRequirement `json:"security,omitempty"`
	// An alternative server array to service this operation. If an alternative server object is specified at the Path Item Object or Root level, it will be overridden by this value.
	Servers []Server `json:"servers,omitempty"`
}

Describes a single API operation on a path.

func GetOperation

func GetOperation(fnOrType any) *Operation

Gets the operation on the function instance or type or returns nil if the type does not implement HasAPIOperation.

func (*Operation) AddParameters

func (op *Operation) AddParameters(build *Builder, in ParameterIn, typ reflect.Type)

Given a struct which has fields representing parameters it will add each property in the generated schema as a parameter to this operation.

func (*Operation) GetParameters

func (op *Operation) GetParameters(in ParameterIn) []Parameter

func (*Operation) GetParametersSchema

func (op *Operation) GetParametersSchema(in ParameterIn) Schema

func (Operation) Merge

func (base Operation) Merge(next Operation) Operation

Merges operations

type Parameter

type Parameter struct {
	// // Allows for an external definition of this parameter.
	*Reference

	// REQUIRED. The name of the parameter. Parameter names are case sensitive.
	//   - If in is "path", the name field MUST correspond to a template expression occurring within the path field in the Paths Object. See Path Templating for further information.
	//   - If in is "header" and the name field is "Accept", "Content-Type" or "Authorization", the parameter definition SHALL be ignored.
	//   - For all other cases, the name corresponds to the parameter name used by the in property.
	Name string `json:"name"`
	// REQUIRED. The location of the parameter. Possible values are "query", "header", "path" or "cookie".
	In ParameterIn `json:"in"`

	ParameterBase
	// contains filtered or unexported fields
}

Describes a single operation parameter.

A unique parameter is defined by a combination of a name and location.

func (Parameter) GetName

func (hr Parameter) GetName() *string

func (Parameter) GetReference

func (hr Parameter) GetReference() *Reference

func (Parameter) GetReferencePrefix

func (hr Parameter) GetReferencePrefix() string

func (Parameter) IsUnique

func (base Parameter) IsUnique(next Parameter) bool

func (Parameter) Merge

func (base Parameter) Merge(next Parameter) Parameter

Merges parameter

func (*Parameter) SetReference

func (hr *Parameter) SetReference(ref string)

type ParameterBase

type ParameterBase struct {
	// A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// Determines whether this parameter is mandatory. If the parameter location is "path", this property is REQUIRED and its value MUST be true. Otherwise, the property MAY be included and its default value is false.
	Required bool `json:"required,omitempty"`
	// Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is false.
	Deprecated bool `json:"deprecated,omitempty"`
	// Sets the ability to pass empty-valued parameters. This is valid only for query parameters and allows sending a parameter with an empty value. Default value is false. If style is used, and if behavior is n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision.
	AllowEmptyValue bool `json:"allowEmptyValue,omitempty"`
	// Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of in): for query - form; for path - simple; for header - simple; for cookie - form.
	Style Style `json:"style,omitempty"`
	// When this is true, parameter values of type array or object generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When style is form, the default value is true. For all other styles, the default value is false.
	Explode bool `json:"explode,omitempty"`
	// Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding. This property only applies to parameters with an in value of query. The default value is false.
	AllowReserved bool `json:"allowReserved,omitempty"`
	// The schema defining the type used for the parameter.
	Schema *Schema `json:"schema,omitempty"`
	// Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The example field is mutually exclusive of the examples field. Furthermore, if referencing a schema that contains an example, the example value SHALL override the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary.
	Example *any `json:"example,omitempty"`
	// Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The examples field is mutually exclusive of the example field. Furthermore, if referencing a schema that contains an example, the examples value SHALL override the example provided by the schema.
	Examples map[string]any `json:"examples,omitempty"`
	// A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry.
	Content Contents `json:"content,omitempty"`
}

A base type shared between Parameter and Header

func (ParameterBase) Merge

func (base ParameterBase) Merge(next ParameterBase) ParameterBase

Merges parameter base type

type ParameterIn

type ParameterIn string

Parameter Locations There are four possible parameter locations specified by the in field:

  • path: Used together with Path Templating, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in /items/{itemId}, the path parameter is itemId.
  • query: Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id.
  • header: Custom headers that are expected as part of the request. Note that RFC7230 states header names are case insensitive.
  • cookie: Used to pass a specific cookie value to the API.
const (
	// Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id.
	ParameterInQuery ParameterIn = "query"
	// Custom headers that are expected as part of the request. Note that RFC7230 states header names are case insensitive.
	ParameterInHeader ParameterIn = "header"
	// Used together with Path Templating, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in /items/{itemId}, the path parameter is itemId.
	ParameterInPath ParameterIn = "path"
	// Used to pass a specific cookie value to the API.
	ParameterInCookie ParameterIn = "cookie"
)

type Path

type Path struct {
	// Allows for an external definition of this path item. The referenced structure MUST be in the format of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined.
	*Reference

	// An optional, string summary, intended to apply to all operations in this path.
	Summary string `json:"summary,omitempty"`
	// An optional, string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// A definition of a GET operation on this path.
	Get *Operation `json:"get,omitempty"`
	// A definition of a PUT operation on this path.
	Put *Operation `json:"put,omitempty"`
	// A definition of a POST operation on this path.
	Post *Operation `json:"post,omitempty"`
	// A definition of a DELETE operation on this path.
	Delete *Operation `json:"delete,omitempty"`
	// A definition of an OPTIONS operation on this path.
	Options *Operation `json:"options,omitempty"`
	// A definition of a HEAD operation on this path.
	Head *Operation `json:"head,omitempty"`
	// A definition of a PATCH operation on this path.
	Patch *Operation `json:"patch,omitempty"`
	// A definition of a TRACE operation on this path.
	Trace *Operation `json:"trace,omitempty"`
	// An alternative server array to service all operations in this path.
	Servers []Server `json:"servers,omitempty"`
	// A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.
	Parameters []Parameter `json:"parameters,omitempty"`
	// contains filtered or unexported fields
}

Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.

func (Path) GetName

func (hr Path) GetName() *string

func (Path) GetReference

func (hr Path) GetReference() *Reference

func (Path) GetReferencePrefix

func (hr Path) GetReferencePrefix() string

func (Path) Merge

func (base Path) Merge(next Path) Path

Merges paths

func (*Path) SetReference

func (hr *Path) SetReference(ref string)

type Reference

type Reference struct {
	// REQUIRED. The reference string.
	Ref string `json:"$ref,omitempty"`
}

A simple object to allow referencing other components in the specification, internally and externally.

The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules.

For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification.

func RefTo

func RefTo(canRef HasReference, name string) *Reference

Returns a reference to the given resource with the given name.

func (*Reference) GetReference

func (hr *Reference) GetReference() *Reference

func (Reference) GetReferencePrefix

func (hr Reference) GetReferencePrefix() string

func (*Reference) SetReference

func (hr *Reference) SetReference(ref string)

type RequestBody

type RequestBody struct {
	// Allows for an external definition of this request body.
	*Reference

	// A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*
	Content Contents `json:"content,omitempty"`
	// Determines if the request body is required in the request. Defaults to false.
	Required bool `json:"required,omitempty"`
	// contains filtered or unexported fields
}

Describes a single request body.

func (RequestBody) GetName

func (hr RequestBody) GetName() *string

func (RequestBody) GetReference

func (hr RequestBody) GetReference() *Reference

func (RequestBody) GetReferencePrefix

func (hr RequestBody) GetReferencePrefix() string

func (RequestBody) Merge

func (base RequestBody) Merge(next RequestBody) RequestBody

Merges request bodies

func (*RequestBody) SetReference

func (hr *RequestBody) SetReference(ref string)

type Response

type Response struct {
	// Allows for an external definition of this response.
	*Reference

	// REQUIRED. A short description of the response. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description"`
	// Maps a header name to its definition. RFC7230 states header names are case insensitive. If a response header is defined with the name "Content-Type", it SHALL be ignored.
	Headers Headers `json:"headers,omitempty"`
	// A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*
	Content Contents `json:"content,omitempty"`
	// A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects.
	Links Links `json:"links,omitempty"`
	// contains filtered or unexported fields
}

Describes a single response from an API Operation, including design-time, static links to operations based on the response.

func (Response) GetName

func (hr Response) GetName() *string

func (Response) GetReference

func (hr Response) GetReference() *Reference

func (Response) GetReferencePrefix

func (hr Response) GetReferencePrefix() string

func (Response) Merge

func (base Response) Merge(next Response) Response

Merges a response

func (*Response) SetReference

func (hr *Response) SetReference(ref string)

type Responses

type Responses map[string]*Response

A container for the expected responses of an operation. The container maps a HTTP response code to the expected response.

The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. However, documentation is expected to cover a successful operation response and any known errors.

The default MAY be used as a default response object for all HTTP codes that are not covered individually by the specification.

The Responses Object MUST contain at least one response code, and it SHOULD be the response for a successful operation call.

type Schema

type Schema struct {
	// Allows for an external definition of this schema.
	*Reference

	// The schema type, if there is only one known
	Type DataType `json:"type,omitempty"`
	// The title and description keywords must be strings. A “title” will preferably be short, whereas a “description” will provide a more lengthy explanation about the purpose of the data described by the schema.
	Title string `json:"title,omitempty"`
	// The title and description keywords must be strings. A “title” will preferably be short, whereas a “description” will provide a more lengthy explanation about the purpose of the data described by the schema.
	Description string `json:"description,omitempty"`
	// Numbers can be restricted to a multiple of a given number, using the multipleOf keyword. It may be set to any positive number.
	MultipleOf int `json:"multipleOf,omitempty"`
	// Ranges of numbers are specified using a combination of the minimum and maximum keywords, (or exclusiveMinimum and exclusiveMaximum for expressing exclusive range).
	Maximum *int `json:"maximum,omitempty"`
	// Ranges of numbers are specified using a combination of the minimum and maximum keywords, (or exclusiveMinimum and exclusiveMaximum for expressing exclusive range).
	ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
	// Ranges of numbers are specified using a combination of the minimum and maximum keywords, (or exclusiveMinimum and exclusiveMaximum for expressing exclusive range).
	Minimum *int `json:"minimum,omitempty"`
	// Ranges of numbers are specified using a combination of the minimum and maximum keywords, (or exclusiveMinimum and exclusiveMaximum for expressing exclusive range).
	ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
	// The length of a string can be constrained using the minLength and maxLength keywords. For both keywords, the value must be a non-negative number.
	MaxLength int `json:"maxLength,omitempty"`
	// The length of a string can be constrained using the minLength and maxLength keywords. For both keywords, the value must be a non-negative number.
	MinLength *int `json:"minLength,omitempty"`
	// (This string SHOULD be a valid regular expression, according to the Ecma-262 Edition 5.1 regular expression dialect)
	Pattern string `json:"pattern,omitempty"`
	// The length of the array can be specified using the minItems and maxItems keywords. The value of each keyword must be a non-negative number. These keywords work whether doing list validation or Tuple validation.
	MaxItems int `json:"maxItems,omitempty"`
	// The length of the array can be specified using the minItems and maxItems keywords. The value of each keyword must be a non-negative number. These keywords work whether doing list validation or Tuple validation.
	MinItems *int `json:"minItems,omitempty"`
	// A schema can ensure that each of the items in an array is unique. Simply set the uniqueItems keyword to true.
	UniqueItems bool `json:"uniqueItems,omitempty"`
	// The number of properties on an object can be restricted using the minProperties and maxProperties keywords. Each of these must be a non-negative integer.
	MaxProperties int `json:"maxProperties,omitempty"`
	// The number of properties on an object can be restricted using the minProperties and maxProperties keywords. Each of these must be a non-negative integer.
	MinProperties *int `json:"minProperties,omitempty"`
	// By default, the properties defined by the properties keyword are not required. However, one can provide a list of required properties using the required keyword.
	Required []string `json:"required,omitempty"`
	// The enum keyword is used to restrict a value to a fixed set of values. It must be an array with at least one element, where each element is unique.
	Enum []any `json:"enum,omitempty"`
	// The format keyword allows for basic semantic identification of certain kinds of string values that are commonly used. For example, because JSON doesn’t have a “DateTime” type, dates need to be encoded as strings. format allows the schema author to indicate that the string value should be interpreted as a date. By default, format is just an annotation and does not effect validation.
	// Examples:
	//   - "date-time": Date and time together, for example, 2018-11-13T20:20:39+00:00.
	//   - "time": Time, for example, 20:20:39+00:00
	//   - "date": Date, for example, 2018-11-13.
	//   - "password": Provides a hint that the string may contain sensitive information.
	// 	 - "byte": Any integer number.
	//   - "binary": Binary data, used to represent the contents of a file.
	//   - "duration": A duration as defined by the ISO 8601 ABNF for “duration”. For example, P3D expresses a duration of 3 days.
	//   - "email": Internet email address, see RFC 5321, section 4.1.2.
	//   - "idn-email": New in draft 7 The internationalized form of an Internet email address, see RFC 6531.
	//   - "hostname": Internet host name, see RFC 1123, section 2.1.
	//   - "idn-hostname": New in draft 7 An internationalized Internet host name, see RFC5890, section 2.3.2.3.
	//   - "ipv4": IPv4 address, according to dotted-quad ABNF syntax as defined in RFC 2673, section 3.2.
	//   - "ipv6": IPv6 address, as defined in RFC 2373, section 2.2.
	//   - "uuid": New in draft 2019-09 A Universally Unique Identifier as defined by RFC 4122. Example: 3e4666bf-d5e5-4aa7-b8ce-cefe41c7568a
	//   - "uri": A universal resource identifier (URI), according to RFC3986.
	//   - "uri-reference": New in draft 6 A URI Reference (either a URI or a relative-reference), according to RFC3986, section 4.1.
	//   - "iri": New in draft 7 The internationalized equivalent of a “uri”, according to RFC3987.
	//   - "iri-reference": New in draft 7 The internationalized equivalent of a “uri-reference”, according to RFC3987
	//   - "uri-template": New in draft 6 A URI Template (of any level) according to RFC6570. If you don’t already know what a URI Template is, you probably don’t need this value.
	//   - "json-pointer": New in draft 6 A JSON Pointer, according to RFC6901. There is more discussion on the use of JSON Pointer within JSON Schema in Structuring a complex schema. Note that this should be used only when the entire string contains only JSON Pointer content, e.g. /foo/bar. JSON Pointer URI fragments, e.g. #/foo/bar/ should use "uri-reference".
	//   - "relative-json-pointer": New in draft 7 A relative JSON pointer.
	//   - "regex": New in draft 7 A regular expression, which should be valid according to the ECMA 262 dialect.
	//   - "float": 32-bit floating point number.
	//   - "double": 64-bit floating point number.
	//   - "int32": 32-bit integer.
	//   - "int64": 64-bit integer.
	Format string `json:"format,omitempty"`
	// The default value for this schema.
	Default *any `json:"default,omitempty"`
	// Must be valid against all of the subschemas
	AllOf []Schema `json:"allOf,omitempty"`
	// Must be valid against exactly one of the subschemas
	OneOf []Schema `json:"oneOf,omitempty"`
	// Must be valid against any of the subschemas
	AnyOf []Schema `json:"anyOf,omitempty"`
	// Must not be valid against the given schema
	Not *Schema `json:"not,omitempty"`
	// List validation is useful for arrays of arbitrary length where each item matches the same schema. For this kind of array, set the items keyword to a single schema that will be used to validate all of the items in the array.
	Items *Schema `json:"items,omitempty"`
	// The properties (key-value pairs) on an object are defined using the properties keyword. The value of properties is an object, where each key is the name of a property and each value is a schema used to validate that property. Any property that doesn’t match any of the property names in the properties keyword is ignored by this keyword.
	Properties map[string]Schema `json:"properties,omitempty"`
	// The additionalProperties keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the properties keyword.
	AdditionalProperties *BoolSchema `json:"additionalProperties,omitempty"`
	// A true value adds "null" to the allowed type specified by the type keyword, only if type is explicitly defined within the same Schema Object. Other Schema Object constraints retain their defined behavior, and therefore may disallow the use of null as a value. A false value leaves the specified or default type unmodified. The default value is false.
	Nullable bool `json:"nullable,omitempty"`
	// Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See Composition and Inheritance for more details.
	Discriminator *Discriminator `json:"discriminator,omitempty"`
	// Relevant only for Schema "properties" definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as readOnly being true and is in the required list, the required will take effect on the response only. A property MUST NOT be marked as both readOnly and writeOnly being true. Default value is false.
	ReadOnly bool `json:"readOnly,omitempty"`
	// Relevant only for Schema "properties" definitions. Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as writeOnly being true and is in the required list, the required will take effect on the request only. A property MUST NOT be marked as both readOnly and writeOnly being true. Default value is false.
	WriteOnly bool `json:"writeOnly,omitempty"`
	// This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property.
	XML *XML `json:"xml,omitempty"`
	// Additional external documentation for this schema.
	ExternalDocs *ExternalDoc `json:"externalDocs,omitempty"`
	// A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary.
	Example *any `json:"example,omitempty"`
	// Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is false.
	Deprecated bool `json:"deprecated,omitempty"`
	// contains filtered or unexported fields
}

The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the JSON Schema Specification Wright Draft 00.

For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated otherwise, the property definitions follow the JSON Schema.

func GetSchema

func GetSchema(valueOrType any) (*Schema, bool)

Gets the defined schema for the given type and if its the full schema, or returns nil if the type does not implement HasFullSchema or HasBaseSchema.

func SchemaOf added in v0.3.2

func SchemaOf[V any](build *Builder) *Schema

Returns the built schema of the given type.

func SchemaRef added in v0.3.2

func SchemaRef(name string) *Schema

Returns a reference to the given resource with the given name.

func (*Schema) AsReference

func (hr *Schema) AsReference() *Schema

func (Schema) GetName

func (s Schema) GetName() *string

func (*Schema) GetPattern

func (s *Schema) GetPattern() *regexp.Regexp

func (Schema) GetReference

func (hr Schema) GetReference() *Reference

func (Schema) GetReferencePrefix

func (hr Schema) GetReferencePrefix() string

func (Schema) Merge

func (base Schema) Merge(next Schema) Schema

func (*Schema) ResolveReference

func (s *Schema) ResolveReference() *Schema

func (*Schema) SetReference

func (hr *Schema) SetReference(ref string)

type Security

type Security struct {
	// Allows for an external definition of this security.
	*Reference

	// REQUIRED. The type of the security scheme. Valid values are "apiKey", "http", "oauth2", "openIdConnect".
	Type SecurityType `json:"type"`
	// A short description for security scheme. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// REQUIRED (with apiKey). The name of the header, query or cookie parameter to be used.
	Name string `json:"name,omitempty"`
	// REQUIRED (with apiKey). The location of the API key. Valid values are "query", "header" or "cookie".
	In ParameterIn `json:"in,omitempty"`
	// REQUIRED (with http). The name of the HTTP Authorization scheme to be used in the Authorization header as defined in RFC7235. The values used SHOULD be registered in the IANA Authentication Scheme registry.
	Scheme string `json:"scheme,omitempty"`
	// (with http) A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes.
	BearerFormat string `json:"bearerFormat,omitempty"`
	// REQUIRED (with oauth2). An object containing configuration information for the flow types supported.
	Flows any `json:"flows,omitempty"`
	// REQUIRED (with openIdConnect). OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL.
	OpenIdConnectUrl string `json:"openIdConnectUrl,omitempty"`
	// contains filtered or unexported fields
}

Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in RFC6749, and OpenID Connect Discovery.

func (Security) GetName

func (hr Security) GetName() *string

func (Security) GetReference

func (hr Security) GetReference() *Reference

func (Security) GetReferencePrefix

func (hr Security) GetReferencePrefix() string

func (Security) IsUnique

func (base Security) IsUnique(next Security) bool

If the two are equivalent

func (*Security) SetReference

func (hr *Security) SetReference(ref string)

type SecurityRequirement

type SecurityRequirement map[string][]string

Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object.

Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information.

When a list of Security Requirement Objects is defined on the OpenAPI Object or Operation Object, only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request.

type SecurityType

type SecurityType string

A security type

const (
	SecurityTypeHTTP          SecurityType = "http"
	SecurityTypeApiKey        SecurityType = "apiKey"
	SecurityTypeOauth2        SecurityType = "oauth2"
	SecurityTypeOpenIDConnect SecurityType = "openIdConnect"
)

type Server

type Server struct {
	// REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in {brackets}.
	URL string `json:"url"`
	// An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// A map between a variable name and its value. The value is used for substitution in the server's URL template.
	Variables ServerVariables `json:"variables,omitempty"`
}

An object representing a Server.

func (Server) IsUnique

func (base Server) IsUnique(next Server) bool

Are the servers equal?

type ServerVariable

type ServerVariable struct {
	// An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty.
	Enum []string `json:"enum,omitempty"`
	// REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is not supplied. Note this behavior is different than the Schema Object's treatment of default values, because in those cases parameter values are optional. If the enum is defined, the value SHOULD exist in the enum's values.
	Default string `json:"default,omitempty"`
	// An optional description for the server variable. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
}

An object representing a Server Variable for server URL template substitution.

type ServerVariables

type ServerVariables map[string]ServerVariable

Helper type to make building server variables cleaner.

type Style

type Style string

In order to support common ways of serializing simple parameters, a set of style values are defined. https://swagger.io/docs/specification/serialization/

const (
	// type(primitive, array, object), in(path), Path-style parameters defined by RFC6570
	ParameterStyleMatrix Style = "matrix"
	// type(primitive, array, object), in(path), Label style parameters defined by RFC6570
	ParameterStyleLabel Style = "label"
	// type(primitive, array, object), in(query, cookie), Form style parameters defined by RFC6570. This option replaces collectionFormat with a csv (when explode is false) or multi (when explode is true) value from OpenAPI 2.0.
	ParameterStyleForm Style = "form"
	// type(array), in(path, header), Simple style parameters defined by RFC6570. This option replaces collectionFormat with a csv value from OpenAPI 2.0.
	ParameterStyleSimple Style = "simple"
	// type(array), in(query), Space separated array values. This option replaces collectionFormat equal to ssv from OpenAPI 2.0.
	ParameterStyleSpaceDelimited Style = "spaceDelimited"
	// type(array), in(query), Pipe separated array values. This option replaces collectionFormat equal to pipes from OpenAPI 2.0.
	ParameterStylePipeDelimited Style = "pipeDelimited"
	// type(object), in(query), Provides a simple way of rendering nested objects using form parameters.
	ParameterStyleDeepObject Style = "deepObject"
)

type Tag

type Tag struct {
	// REQUIRED. The name of the tag.
	Name string `json:"name"`
	// A short description for the tag. CommonMark syntax MAY be used for rich text representation.
	Description string `json:"description,omitempty"`
	// Additional external documentation for this tag.
	ExternalDocs *ExternalDoc `json:"externalDocs,omitempty"`
}

Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.

func (Tag) IsUnique

func (base Tag) IsUnique(next Tag) bool

If the two tags are pointing to the same one

type XML

type XML struct {
	// Replaces the name of the element/attribute used for the described schema property. When defined within items, it will affect the name of the individual XML elements within the list. When defined alongside type being array (outside the items), it will affect the wrapping element and only if wrapped is true. If wrapped is false, it will be ignored.
	Name string `json:"name,omitempty"`
	// The URI of the namespace definition. Value MUST be in the form of an absolute URI.
	Namespace string `json:"namespace,omitempty"`
	// The prefix to be used for the name.
	Prefix string `json:"prefix,omitempty"`
	// Declares whether the property definition translates to an attribute instead of an element. Default value is false.
	Attribute bool `json:"attribute,omitempty"`
	// MAY be used only for an array definition. Signifies whether the array is wrapped (for example, <books><book/><book/></books>) or unwrapped (<book/><book/>). Default value is false. The definition takes effect only when defined alongside type being array (outside the items).
	Wrapped bool `json:"wrapped,omitempty"`
}

A metadata object that allows for more fine-tuned XML model definitions.

When using arrays, XML element names are not inferred (for singular/plural forms) and the name property SHOULD be used to add that information. See examples for expected behavior.

Jump to

Keyboard shortcuts

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