Documentation ¶
Overview ¶
Copyright 2024 Arianit Uka
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright 2020 Daniel G. Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright 2020 Daniel G. Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright 2020 Daniel G. Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright 2020 Daniel G. Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright 2024 Arianit Uka ¶
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright 2020 Daniel G. Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Index ¶
- Constants
- Variables
- func DefaultSchemaNamer(t reflect.Type, hint string) string
- func Scalar(openAPI *OpenAPI, configuration map[string]any) []byte
- func Validate(r Registry, s *Schema, path *PathBuffer, mode ValidateMode, v any, ...)
- type AddOpFunc
- type Builder
- func (b *Builder) ApiKeyAuth(header string) *Builder
- func (b *Builder) BasicAuth() *Builder
- func (b *Builder) BearerAuth() *Builder
- func (b *Builder) Contact() *Builder
- func (b *Builder) Description(description string) *Builder
- func (b *Builder) License() *Builder
- func (b *Builder) OAuth2() *OAuth2Builder
- func (b *Builder) OpenAPI() *OpenAPI
- func (b *Builder) OpenID(url string) *Builder
- func (b *Builder) Register(op *Operation) *OperationBuilder
- func (b *Builder) Registry() Registry
- func (b *Builder) Security(securitySchema string, params []string) *Builder
- func (b *Builder) SecurityScheme(name string, scheme *SecurityScheme) *Builder
- func (b *Builder) Server() *ServerBuilder
- func (b *Builder) TermsOfService(url string) *Builder
- type Components
- type Contact
- type ContactBuilder
- type Encoding
- type ErrorDetail
- type Example
- type ExampleBuilder
- func (eb *ExampleBuilder) Description(description string) *ExampleBuilder
- func (eb *ExampleBuilder) ExternalValue(uri string) *ExampleBuilder
- func (eb *ExampleBuilder) Ref(ref string)
- func (eb *ExampleBuilder) Summary(summary string) *ExampleBuilder
- func (eb *ExampleBuilder) Value(value any) *ExampleBuilder
- type ExternalDocs
- type Header
- type Info
- type License
- type LicenseBuilder
- type Link
- type LinkBuilder
- func (lb *LinkBuilder) AddParam(name string, expression any) *LinkBuilder
- func (lb *LinkBuilder) Description(description string) *LinkBuilder
- func (lb *LinkBuilder) OperationID(operationID string) *LinkBuilder
- func (lb *LinkBuilder) OperationRef(operationRef string) *LinkBuilder
- func (lb *LinkBuilder) RequestBody(expression any) *LinkBuilder
- func (lb *LinkBuilder) Server() *ServerBuilder
- type MediaType
- type MediaTypeBuilder
- type ModelValidator
- type OAuth2Builder
- type OAuthFlow
- type OAuthFlowBuilder
- type OAuthFlows
- type OpenAPI
- type Operation
- type OperationBuilder
- func (ob *OperationBuilder) Callback(event string, op *Operation) *OperationBuilder
- func (ob *OperationBuilder) Description(description string) *OperationBuilder
- func (ob *OperationBuilder) Request() *RequestBuilder
- func (ob *OperationBuilder) Response(status int) *ResponseBuilder
- func (ob *OperationBuilder) Security(securitySchema string, params []string) *OperationBuilder
- func (ob *OperationBuilder) Server() *ServerBuilder
- func (ob *OperationBuilder) Summary(summary string) *OperationBuilder
- func (ob *OperationBuilder) Tag(tag string) *OperationBuilder
- type Param
- type ParamBuilder
- func (pb *ParamBuilder) AddExample(name string) *ExampleBuilder
- func (pb *ParamBuilder) Description(description string) *ParamBuilder
- func (pb *ParamBuilder) Example(example string) *ParamBuilder
- func (pb *ParamBuilder) Explode(explode bool) *ParamBuilder
- func (pb *ParamBuilder) In(in string) *ParamBuilder
- func (pb *ParamBuilder) Required(required bool) *ParamBuilder
- func (pb *ParamBuilder) Style(style string) *ParamBuilder
- type PathBuffer
- type PathItem
- type Registry
- type RequestBody
- type RequestBodyBuilder
- func (rbb *RequestBodyBuilder) AddExample(example string) *ExampleBuilder
- func (rbb *RequestBodyBuilder) Description(description string) *RequestBodyBuilder
- func (rbb *RequestBodyBuilder) Example(example string) *RequestBodyBuilder
- func (rbb *RequestBodyBuilder) Required(required bool) *RequestBodyBuilder
- type RequestBuilder
- func (rb *RequestBuilder) Body(f any) *RequestBodyBuilder
- func (rb *RequestBuilder) ContentType(contentType string) *RequestBuilder
- func (rb *RequestBuilder) CookieParam(name string, f any) *ParamBuilder
- func (rb *RequestBuilder) DefaultContentType(contentType string) *RequestBuilder
- func (rb *RequestBuilder) Param(in string, name string, f any) *ParamBuilder
- func (rb *RequestBuilder) PathParam(name string, f any) *ParamBuilder
- func (rb *RequestBuilder) QueryParam(name string, f any) *ParamBuilder
- type Response
- type ResponseBuilder
- func (rb *ResponseBuilder) Body(f any) *MediaTypeBuilder
- func (rb *ResponseBuilder) ContentType(contentType string) *ResponseBuilder
- func (rb *ResponseBuilder) DefaultContentType(contentType string) *ResponseBuilder
- func (rb *ResponseBuilder) Header(name string, f any) *ParamBuilder
- func (rb *ResponseBuilder) Link(name string) *LinkBuilder
- type Schema
- type SchemaProvider
- type SecurityScheme
- type Server
- type ServerBuilder
- type ServerVariable
- type ServerVariableBuilder
- type Tag
- type ValidateMode
- type ValidateResult
Constants ¶
const ( TypeBoolean = "boolean" TypeInteger = "integer" TypeNumber = "number" TypeString = "string" TypeArray = "array" TypeObject = "object" )
JSON Schema type constants
Variables ¶
var ( IntType = int(0) Int8Type = int8(0) Int16Type = int16(0) Int32Type = int32(0) Int64Type = int64(0) UintType = uint(0) Uint8Type = uint8(0) Uint16Type = uint16(0) Uint32Type = uint32(0) Uint64Type = uint64(0) UintPtrType = uintptr(0) Float32Type = float32(0) Float64Type = float64(0) Complex64Type = complex64(0) Complex128Type = complex128(0) StringType = "" BoolType = false ByteType = byte(0) RuneType = rune(0) )
Basic initialized types that can be easily passed to any Body() in builder.go
var ErrSchemaInvalid = errors.New("schema is invalid")
ErrSchemaInvalid is sent when there is a problem building the schema.
Functions ¶
func DefaultSchemaNamer ¶
DefaultSchemaNamer provides schema names for types. It uses the type name when possible, ignoring the package name. If the type is generic, e.g. `MyType[SubType]`, then the brackets are removed like `MyTypeSubType`. If the type is unnamed, then the name hint is used. Note: if you plan to use types with the same name from different packages, you should implement your own namer function to prevent issues. Nested anonymous types can also present naming issues.
func Validate ¶
func Validate(r Registry, s *Schema, path *PathBuffer, mode ValidateMode, v any, res *ValidateResult)
Validate an input value against a schema, collecting errors in the validation result object. If successful, `res.Errors` will be empty. It is suggested to use a `sync.Pool` to reuse the PathBuffer and ValidateResult objects, making sure to call `Reset()` on them before returning them to the pool.
registry := openapi.NewMapRegistry("#/prefix", openapi.DefaultSchemaNamer) schema := openapi.SchemaFromType(registry, reflect.TypeOf(MyType{})) pb := openapi.NewPathBuffer([]byte(""), 0) res := &openapi.ValidateResult{} var value any json.Unmarshal([]byte(`{"foo": "bar"}`), &v) openapi.Validate(registry, schema, pb, openapi.ModeWriteToServer, value, res) for _, err := range res.Errors { fmt.Println(err.Error()) }
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder provides builders for building an OpenAPI spec from code
func New ¶
New returns an OpenAPI builder that can be used to easily generate OpenAPI specs from code.
func (*Builder) ApiKeyAuth ¶
ApiKeyAuth adds a ApiKeyAuth security schema. We expect the API key to be in a Header and you specify the header as the argument to this function
func (*Builder) BearerAuth ¶
BearerAuth adds a BearerAuth security schema
func (*Builder) Description ¶
Description sets the description for the API
func (*Builder) OAuth2 ¶
func (b *Builder) OAuth2() *OAuth2Builder
func (*Builder) OpenID ¶
OpenID adds a OpenID security schema. url is an OpenId Connect URL to discover OAuth2
func (*Builder) Register ¶
func (b *Builder) Register(op *Operation) *OperationBuilder
Register registers a new Operation.
func (*Builder) SecurityScheme ¶
func (b *Builder) SecurityScheme(name string, scheme *SecurityScheme) *Builder
SecurityScheme adds a custom SecurityScheme.
func (*Builder) TermsOfService ¶
TermsOfService sets url for the terms of service
type Components ¶
type Components struct { // Schemas is an object to hold reusable Schema Objects. Schemas Registry `yaml:"schemas,omitempty"` // Responses is an object to hold reusable Response Objects. Responses map[string]*Response `yaml:"responses,omitempty"` // Parameters is an object to hold reusable Parameter Objects. Parameters map[string]*Param `yaml:"parameters,omitempty"` // Examples is an object to hold reusable Example Objects. Examples map[string]*Example `yaml:"examples,omitempty"` // RequestBodies is an object to hold reusable Request Body Objects. RequestBodies map[string]*RequestBody `yaml:"requestBodies,omitempty"` // Headers is an object to hold reusable Header Objects. Headers map[string]*Header `yaml:"headers,omitempty"` // SecuritySchemes is an object to hold reusable Security Scheme Objects. SecuritySchemes map[string]*SecurityScheme `yaml:"securitySchemes,omitempty"` // Links is an object to hold reusable Link Objects. Links map[string]*Link `yaml:"links,omitempty"` // Callbacks is an object to hold reusable Callback Objects. Callbacks map[string]*PathItem `yaml:"callbacks,omitempty"` // PathItems is an object to hold reusable Path Item Objects. PathItems map[string]*PathItem `yaml:"pathItems,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Components 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.
components: schemas: GeneralError: type: object properties: code: type: integer format: int32 message: type: string Category: type: object properties: id: type: integer format: int64 name: type: string Tag: type: object properties: id: type: integer format: int64 name: type: string parameters: skipParam: name: skip in: query description: number of items to skip required: true schema: type: integer format: int32 limitParam: name: limit in: query description: max records to return required: true schema: type: integer format: int32 responses: NotFound: description: Entity not found. IllegalInput: description: Illegal input for operation. GeneralError: description: General Error content: application/json: schema: $ref: '#/components/schemas/GeneralError' securitySchemes: api_key: type: apiKey name: api_key in: header petstore_auth: type: oauth2 flows: implicit: authorizationUrl: https://example.org/api/oauth/dialog scopes: write:pets: modify pets in your account read:pets: read your pets
func (*Components) MarshalJSON ¶
func (c *Components) MarshalJSON() ([]byte, error)
type Contact ¶
type Contact struct { // Name of the contact person/organization. Name string `yaml:"name,omitempty"` // URL pointing to the contact information. URL string `yaml:"url,omitempty"` // Email address of the contact person/organization. Email string `yaml:"email,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Contact information to get support for the API.
name: API Support url: https://www.example.com/support email: support@example.com
func (*Contact) MarshalJSON ¶
type ContactBuilder ¶
type ContactBuilder struct {
// contains filtered or unexported fields
}
ContactBuilder helps build a contact
func (*ContactBuilder) Email ¶
func (cb *ContactBuilder) Email(email string) *ContactBuilder
Email sets the email for the contact
func (*ContactBuilder) Name ¶
func (cb *ContactBuilder) Name(name string) *ContactBuilder
Name sets the name for the contact
func (*ContactBuilder) URL ¶
func (cb *ContactBuilder) URL(url string) *ContactBuilder
URL sets the URL for the contact
type Encoding ¶
type Encoding struct { // ContentType for encoding a specific property. Default value depends on the // property type: for object - application/json; for array – the default is // defined based on the inner type; for all other cases the default is // application/octet-stream. 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 `yaml:"contentType,omitempty"` // Headers is 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 map[string]*Header `yaml:"headers,omitempty"` // Style 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 or multipart/form-data. If a value is // explicitly defined, then the value of contentType (implicit or explicit) // SHALL be ignored. Style string `yaml:"style,omitempty"` // Explode, when 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 or multipart/form-data. If a value is // explicitly defined, then the value of contentType (implicit or explicit) // SHALL be ignored. Explode *bool `yaml:"explode,omitempty"` // AllowReserved 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 or multipart/form-data. If a value is // explicitly defined, then the value of contentType (implicit or explicit) // SHALL be ignored. AllowReserved bool `yaml:"allowReserved,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Encoding is a single encoding definition applied to a single schema property.
requestBody: content: multipart/form-data: schema: type: object properties: id: # default is text/plain type: string format: uuid address: # default is application/json type: object properties: {} historyMetadata: # need to declare XML format! description: metadata in XML format type: object properties: {} profileImage: {} encoding: historyMetadata: # require XML Content-Type in utf-8 encoding contentType: application/xml; charset=utf-8 profileImage: # only accept png/jpeg contentType: image/png, image/jpeg headers: X-Rate-Limit-Limit: description: The number of allowed requests in the current period schema: type: integer
func (*Encoding) MarshalJSON ¶
type ErrorDetail ¶
type ErrorDetail struct { // Message is a human-readable explanation of the error. Message string `json:"message,omitempty" doc:"Error message text"` // Location is a path-like string indicating where the error occurred. // It typically begins with `path`, `query`, `header`, or `body`. Example: // `body.items[3].tags` or `path.thing-id`. Location string `json:"location,omitempty" doc:"Where the error occurred, e.g. 'body.items[3].tags' or 'path.thing-id'"` // Value is the value at the given location, echoed back to the client // to help with debugging. This can be useful for e.g. validating that // the client didn't send extra whitespace or help when the client // did not log an outgoing request. Value any `json:"value,omitempty" doc:"The value at the given location"` }
ErrorDetail provides details about a specific error.
func (*ErrorDetail) Error ¶
func (e *ErrorDetail) Error() string
Error returns the error message / satisfies the `error` interface. If a location and value are set, they will be included in the error message, otherwise just the message is returned.
func (*ErrorDetail) ErrorDetail ¶
func (e *ErrorDetail) ErrorDetail() *ErrorDetail
ErrorDetail satisfies the `ErrorDetailer` interface.
type Example ¶
type Example struct { // Ref is a reference to another example. This field is mutually exclusive // with the other fields. Ref string `yaml:"$ref,omitempty"` // Summary is a short summary of the example. Summary string `yaml:"summary,omitempty"` // Description is a long description of the example. CommonMark syntax MAY // be used for rich text representation. Description string `yaml:"description,omitempty"` // Value is an 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 `yaml:"value,omitempty"` // ExternalValue is a URI 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. See the rules for resolving Relative References. ExternalValue string `yaml:"externalValue,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Example value of a request param or body or response header or body.
requestBody: content: 'application/json': schema: $ref: '#/components/schemas/Address' examples: foo: summary: A foo example value: {"foo": "bar"} bar: summary: A bar example value: {"bar": "baz"}
func (*Example) MarshalJSON ¶
type ExampleBuilder ¶
type ExampleBuilder struct {
// contains filtered or unexported fields
}
ExampleBuilder helps build examples.
func (*ExampleBuilder) Description ¶
func (eb *ExampleBuilder) Description(description string) *ExampleBuilder
Description sets the description for the example.
func (*ExampleBuilder) ExternalValue ¶
func (eb *ExampleBuilder) ExternalValue(uri string) *ExampleBuilder
ExternalValue sets the ExternalValue
func (*ExampleBuilder) Ref ¶
func (eb *ExampleBuilder) Ref(ref string)
Ref sets the ref of the example. This references another example. $ref: '#/components/examples/objectExample'
func (*ExampleBuilder) Summary ¶
func (eb *ExampleBuilder) Summary(summary string) *ExampleBuilder
Summary sets a summary for an example. This is required.
func (*ExampleBuilder) Value ¶
func (eb *ExampleBuilder) Value(value any) *ExampleBuilder
Value sets the value for the example.
type ExternalDocs ¶
type ExternalDocs struct { // Description of the target documentation. CommonMark syntax MAY be used for // rich text representation. Description string `yaml:"description,omitempty"` // URL is REQUIRED. The URL for the target documentation. Value MUST be in the // format of a URL. URL string `yaml:"url"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
ExternalDocs allows referencing an external resource for extended documentation.
description: Find more info here url: https://example.com
func (*ExternalDocs) MarshalJSON ¶
func (e *ExternalDocs) MarshalJSON() ([]byte, error)
type Header ¶
type Header = Param
Header object follows the structure of the Parameter Object with the following changes:
name MUST NOT be specified, it is given in the corresponding headers map.
in MUST NOT be specified, it is implicitly in header.
All traits that are affected by the location MUST be applicable to a location of header (for example, style).
Example:
description: The number of allowed requests in the current period schema: type: integer
type Info ¶
type Info struct { // Title of the API. Title string `yaml:"title"` // Description of the API. CommonMark syntax MAY be used for rich text representation. Description string `yaml:"description,omitempty"` // TermsOfService URL for the API. TermsOfService string `yaml:"termsOfService,omitempty"` // Contact information to get support for the API. Contact *Contact `yaml:"contact,omitempty"` // License name & link for using the API. License *License `yaml:"license,omitempty"` // Version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version). Version string `yaml:"version"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Info object that 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.
title: Sample Pet Store App summary: A pet store manager. description: This is a sample server for a pet store. termsOfService: https://example.com/terms/ contact: name: API Support url: https://www.example.com/support email: support@example.com license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html version: 1.0.1
func (*Info) MarshalJSON ¶
type License ¶
type License struct { // Name of the license. Name string `yaml:"name"` // Identifier SPDX license expression for the API. This field is mutually // exclusive with the URL field. Identifier string `yaml:"identifier,omitempty"` // URL pointing to the license. This field is mutually exclusive with the // Identifier field. URL string `yaml:"url,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
License name & link for using the API.
name: Apache 2.0 identifier: Apache-2.0
func (*License) MarshalJSON ¶
type LicenseBuilder ¶
type LicenseBuilder struct {
// contains filtered or unexported fields
}
LicenseBuilder helps build a licensea
func (*LicenseBuilder) Identifier ¶
func (lb *LicenseBuilder) Identifier(identifier string) *LicenseBuilder
Identifier sets the identifier
func (*LicenseBuilder) Name ¶
func (lb *LicenseBuilder) Name(name string) *LicenseBuilder
Name sets the license name
func (*LicenseBuilder) URL ¶
func (lb *LicenseBuilder) URL(url string) *LicenseBuilder
URL sets the URL
type Link ¶
type Link struct { // Ref is a reference to another example. This field is mutually exclusive // with the other fields. Ref string `yaml:"$ref,omitempty"` // OperationRef is 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. See the rules for // resolving Relative References. OperationRef string `yaml:"operationRef,omitempty"` // OperationID is 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 `yaml:"operationId,omitempty"` // Parameters is 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 `yaml:"parameters,omitempty"` // RequestBody is a literal value or {expression} to use as a request body // when calling the target operation. RequestBody any `yaml:"requestBody,omitempty"` // Description of the link. CommonMark syntax MAY be used for rich text representation. Description string `yaml:"description,omitempty"` // Server object to be used by the target operation. Server *Server `yaml:"server,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Link object represents a possible design-time link for a response. The presence of a link does not guarantee the caller’s ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations.
Unlike dynamic links (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response.
For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.
paths: /users/{id}: parameters: - name: id in: path required: true description: the user identifier, as userId schema: type: string get: responses: '200': description: the user being returned content: application/json: schema: type: object properties: uuid: # the unique user id type: string format: uuid links: address: # the target link operationId operationId: getUserAddress parameters: # get the `id` field from the request path parameter named `id` userId: $request.path.id # the path item of the linked operation /users/{userid}/address: parameters: - name: userid in: path required: true description: the user identifier, as userId schema: type: string # linked operation get: operationId: getUserAddress responses: '200': description: the user's address
func (*Link) MarshalJSON ¶
type LinkBuilder ¶
type LinkBuilder struct {
// contains filtered or unexported fields
}
LinkBuilder assists with making links
func (*LinkBuilder) AddParam ¶
func (lb *LinkBuilder) AddParam(name string, expression any) *LinkBuilder
AddParam adds a link param, expression is a OpenAPI runtime expressions (see https://swagger.io/docs/specification/links/)
func (*LinkBuilder) Description ¶
func (lb *LinkBuilder) Description(description string) *LinkBuilder
Description sets the description of the link
func (*LinkBuilder) OperationID ¶
func (lb *LinkBuilder) OperationID(operationID string) *LinkBuilder
Set the OperationID of this link.
func (*LinkBuilder) OperationRef ¶
func (lb *LinkBuilder) OperationRef(operationRef string) *LinkBuilder
OperationRef sets the OperationRef for the link.
func (*LinkBuilder) RequestBody ¶
func (lb *LinkBuilder) RequestBody(expression any) *LinkBuilder
RequestBody sets the link request body, expression is an OpenAPI run time expression (see https://swagger.io/docs/specification/links/)
func (*LinkBuilder) Server ¶
func (lb *LinkBuilder) Server() *ServerBuilder
Server adds a server for the link
type MediaType ¶
type MediaType struct { // Schema defining the content of the request, response, or parameter. Schema *Schema `yaml:"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 `yaml:"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 map[string]*Example `yaml:"examples,omitempty"` // Encoding is 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 map[string]*Encoding `yaml:"encoding,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
MediaType object provides schema and examples for the media type identified by its key.
application/json: schema: $ref: "#/components/schemas/Pet" examples: cat: summary: An example of a cat value: name: Fluffy petType: Cat color: White gender: male breed: Persian
func (*MediaType) MarshalJSON ¶
type MediaTypeBuilder ¶
type MediaTypeBuilder struct {
// contains filtered or unexported fields
}
func (*MediaTypeBuilder) AddExample ¶
func (mtb *MediaTypeBuilder) AddExample(name string) *ExampleBuilder
AddExample adds an example with a name.
func (*MediaTypeBuilder) Example ¶
func (mtb *MediaTypeBuilder) Example(example string) *MediaTypeBuilder
Example sets the example for this media type
func (*MediaTypeBuilder) Schema ¶
func (mtb *MediaTypeBuilder) Schema(f any)
Schema overrides the schema with the type f
type ModelValidator ¶
type ModelValidator struct {
// contains filtered or unexported fields
}
ModelValidator is a utility for validating e.g. JSON loaded data against a Go struct model. It is not goroutine-safe and should not be used in HTTP handlers! Schemas are generated on-the-fly on first use and re-used on subsequent calls. This utility can be used to easily validate data outside of the normal request/response flow, for example on application startup:
type MyExample struct { Name string `json:"name" maxLength:"5"` Age int `json:"age" minimum:"25"` } var value any json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &value) validator := ModelValidator() errs := validator.Validate(reflect.TypeOf(MyExample{}), value) if errs != nil { fmt.Println("Validation error", errs) }
func NewModelValidator ¶
func NewModelValidator() *ModelValidator
NewModelValidator creates a new model validator with all the components it needs to create schemas, validate them, and return any errors.
func (*ModelValidator) Validate ¶
func (v *ModelValidator) Validate(typ reflect.Type, value any) []error
Validate the inputs. The type should be the Go struct with validation field tags and the value should be e.g. JSON loaded into an `any`. A list of errors is returned if validation failed, otherwise `nil`.
type MyExample struct { Name string `json:"name" maxLength:"5"` Age int `json:"age" minimum:"25"` } var value any json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &value) validator := ModelValidator() errs := validator.Validate(reflect.TypeOf(MyExample{}), value) if errs != nil { fmt.Println("Validation error", errs) }
type OAuth2Builder ¶
type OAuth2Builder struct {
// contains filtered or unexported fields
}
OAuth2Builder helps build OAuth2
func (*OAuth2Builder) AuthorizationCode ¶
func (ob *OAuth2Builder) AuthorizationCode() *OAuthFlowBuilder
AuthorizationCode sets the AuthorizationCode flow
func (*OAuth2Builder) ClientCredentials ¶
func (ob *OAuth2Builder) ClientCredentials() *OAuthFlowBuilder
ClientCredentials sets the ClientCredentials flow
func (*OAuth2Builder) Implicit ¶
func (ob *OAuth2Builder) Implicit() *OAuthFlowBuilder
Implicit sets the Implicit flow
func (*OAuth2Builder) Password ¶
func (ob *OAuth2Builder) Password() *OAuthFlowBuilder
Password sets the Password flow
type OAuthFlow ¶
type OAuthFlow struct { // AuthorizationURL is REQUIRED for `implicit` and `authorizationCode` flows. // The authorization URL to be used for this flow. This MUST be in the form of // a URL. The OAuth2 standard requires the use of TLS. AuthorizationURL string `yaml:"authorizationUrl,omitempty"` // TokenURL is REQUIRED. The token URL to be used for this flow. This MUST be // in the form of a URL. The OAuth2 standard requires the use of TLS. TokenURL string `yaml:"tokenUrl"` // RefreshURL is the URL to be used for obtaining refresh tokens. This MUST be // in the form of a URL. The OAuth2 standard requires the use of TLS. RefreshURL string `yaml:"refreshUrl,omitempty"` // Scopes are REQUIRED. The available scopes for the OAuth2 security scheme. A // map between the scope name and a short description for it. The map MAY be // empty. Scopes map[string]string `yaml:"scopes"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
OAuthFlow stores configuration details for a supported OAuth Flow.
type: oauth2 flows: implicit: authorizationUrl: https://example.com/api/oauth/dialog scopes: write:pets: modify pets in your account read:pets: read your pets authorizationCode: authorizationUrl: https://example.com/api/oauth/dialog tokenUrl: https://example.com/api/oauth/token scopes: write:pets: modify pets in your account read:pets: read your pets
func (*OAuthFlow) MarshalJSON ¶
type OAuthFlowBuilder ¶
type OAuthFlowBuilder struct {
// contains filtered or unexported fields
}
OAuthFlowBuilder helps build a oauth flow
func (*OAuthFlowBuilder) AuthorizationURL ¶
func (b *OAuthFlowBuilder) AuthorizationURL(url string) *OAuthFlowBuilder
AuthorizationURL sets the authorization url for the flow
func (*OAuthFlowBuilder) RefreshURL ¶
func (b *OAuthFlowBuilder) RefreshURL(url string) *OAuthFlowBuilder
RefreshURL sets the refresh url for the flow
func (*OAuthFlowBuilder) Scopes ¶
func (b *OAuthFlowBuilder) Scopes(scopes map[string]string) *OAuthFlowBuilder
Scopes sets the scope for the flow
func (*OAuthFlowBuilder) TokenURL ¶
func (b *OAuthFlowBuilder) TokenURL(url string) *OAuthFlowBuilder
TokenURL sets the token url for the flow
type OAuthFlows ¶
type OAuthFlows struct { // Implicit is the configuration for the OAuth Implicit flow. Implicit *OAuthFlow `yaml:"implicit,omitempty"` // Password is the configuration for the OAuth Resource Owner Password flow. Password *OAuthFlow `yaml:"password,omitempty"` // ClientCredentials is the configuration for the OAuth Client Credentials // flow. Previously called application in OpenAPI 2.0. ClientCredentials *OAuthFlow `yaml:"clientCredentials,omitempty"` // AuthorizationCode is the configuration for the OAuth Authorization Code // flow. Previously called accessCode in OpenAPI 2.0. AuthorizationCode *OAuthFlow `yaml:"authorizationCode,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
OAuthFlows allows configuration of the supported OAuth Flows.
func (*OAuthFlows) MarshalJSON ¶
func (o *OAuthFlows) MarshalJSON() ([]byte, error)
type OpenAPI ¶
type OpenAPI struct { // OpenAPI is REQUIRED. This string MUST be the version number of the OpenAPI // Specification that the OpenAPI document uses. The openapi field SHOULD be // used by tooling to interpret the OpenAPI document. This is not related to // the API info.version string. OpenAPI string `yaml:"openapi"` // Info is REQUIRED. Provides metadata about the API. The metadata MAY be used // by tooling as required. Info *Info `yaml:"info"` // JSONSchemaDialect is the default value for the $schema keyword within Schema // Objects contained within this OAS document. This MUST be in the form of a // URI. JSONSchemaDialect string `yaml:"jsonSchemaDialect,omitempty"` // Servers is 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 `yaml:"servers,omitempty"` // Paths are the available paths and operations for the API. Paths map[string]*PathItem `yaml:"paths,omitempty"` // Webhooks that MAY be received as part of this API and that the API consumer // MAY choose to implement. Closely related to the callbacks feature, this // section describes requests initiated other than by an API call, for example // by an out of band registration. The key name is a unique string to refer to // each webhook, while the (optionally referenced) Path Item Object describes // a request that may be initiated by the API provider and the expected // responses. An example is available. Webhooks map[string]*PathItem `yaml:"webhooks,omitempty"` // Components is an element to hold various schemas for the document. Components *Components `yaml:"components,omitempty"` // Security is 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 []map[string][]string `yaml:"security,omitempty"` // Tags are a list of tags used by the document 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 `yaml:"tags,omitempty"` // ExternalDocs is additional external documentation. ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` // OnAddOperation is called when an operation is added to the OpenAPI via // `AddOperation`. You may bypass this by directly writing to the `Paths` // map instead. OnAddOperation []AddOpFunc `yaml:"-"` }
OpenAPI is the root object of the OpenAPI document.
func (*OpenAPI) AddOperation ¶
AddOperation adds an operation to the OpenAPI. This is the preferred way to add operations to the OpenAPI, as it will ensure that the operation is properly added to the Paths map, and will call any registered OnAddOperation functions.
func (OpenAPI) Downgrade ¶
Downgrade converts this OpenAPI 3.1 spec to OpenAPI 3.0.3, returning the JSON []byte representation of the downgraded spec. This mostly exists to provide an alternative spec for tools which are not yet 3.1 compatible.
It reverses the changes documented at: https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0
func (*OpenAPI) DowngradeYAML ¶
DowngradeYAML converts this OpenAPI 3.1 spec to OpenAPI 3.0.3, returning the YAML []byte representation of the downgraded spec.
func (*OpenAPI) MarshalJSON ¶
type Operation ¶
type Operation struct { // Method is the HTTP method for this operation Method string `yaml:"-"` // Path is the URL path for this operation Path string `yaml:"-"` // Tags is 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 `yaml:"tags,omitempty"` // Summary is a short summary of what the operation does. Summary string `yaml:"summary,omitempty"` // Description is a verbose explanation of the operation behavior. CommonMark // syntax MAY be used for rich text representation. Description string `yaml:"description,omitempty"` // ExternalDocs describes additional external documentation for this // operation. ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"` // OperationID is a 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 `yaml:"operationId,omitempty"` // Parameters is 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 []*Param `yaml:"parameters,omitempty"` // RequestBody applicable for this operation. The requestBody is fully // 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 (such as GET, HEAD and DELETE), requestBody is permitted // but does not have well-defined semantics and SHOULD be avoided if possible. RequestBody *RequestBody `yaml:"requestBody,omitempty"` // Responses is the list of possible responses as they are returned from // executing this operation. Responses map[string]*Response `yaml:"responses,omitempty"` // Callbacks is 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 map[string]map[string]*PathItem `yaml:"callbacks,omitempty"` // Deprecated declares this operation to be deprecated. Consumers SHOULD // refrain from usage of the declared operation. Default value is false. Deprecated bool `yaml:"deprecated,omitempty"` // Security is 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 []map[string][]string `yaml:"security,omitempty"` // Servers is 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 `yaml:"servers,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Operation describes a single API operation on a path.
tags: - pet summary: Updates a pet in the store with form data operationId: updatePetWithForm parameters: - name: petId in: path description: ID of pet that needs to be updated required: true schema: type: string requestBody: content: 'application/x-www-form-urlencoded': schema: type: object properties: name: description: Updated name of the pet type: string status: description: Updated status of the pet type: string required: - status responses: '200': description: Pet updated. content: 'application/json': {} 'application/xml': {} '405': description: Method Not Allowed content: 'application/json': {} 'application/xml': {} security: - petstore_auth: - write:pets - read:pets
func (*Operation) MarshalJSON ¶
type OperationBuilder ¶
type OperationBuilder struct {
// contains filtered or unexported fields
}
OperationBuilder assists in building an openapi.Operation
func (*OperationBuilder) Callback ¶
func (ob *OperationBuilder) Callback(event string, op *Operation) *OperationBuilder
Callback adds a callback.
func (*OperationBuilder) Description ¶
func (ob *OperationBuilder) Description(description string) *OperationBuilder
Description sets the description
func (*OperationBuilder) Request ¶
func (ob *OperationBuilder) Request() *RequestBuilder
Request returns a RequestBuilder which helps build a request
func (*OperationBuilder) Response ¶
func (ob *OperationBuilder) Response(status int) *ResponseBuilder
Response adds a response with a status code.
func (*OperationBuilder) Security ¶
func (ob *OperationBuilder) Security(securitySchema string, params []string) *OperationBuilder
Security sets the security for this operation
func (*OperationBuilder) Server ¶
func (ob *OperationBuilder) Server() *ServerBuilder
Server adds a server for this operation.
func (*OperationBuilder) Summary ¶
func (ob *OperationBuilder) Summary(summary string) *OperationBuilder
Summary sets the summary.
func (*OperationBuilder) Tag ¶
func (ob *OperationBuilder) Tag(tag string) *OperationBuilder
Tag adds a tag
type Param ¶
type Param struct { // Ref is a reference to another example. This field is mutually exclusive // with the other fields. Ref string `yaml:"$ref,omitempty"` // Name is 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 `yaml:"name,omitempty"` // In is REQUIRED. The location of the parameter. Possible values are "query", // "header", "path" or "cookie". In string `yaml:"in,omitempty"` // Description of the parameter. This could contain examples of use. // CommonMark syntax MAY be used for rich text representation. Description string `yaml:"description,omitempty"` // Required 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 `yaml:"required,omitempty"` // Deprecated specifies that a parameter is deprecated and SHOULD be // transitioned out of usage. Default value is false. Deprecated bool `yaml:"deprecated,omitempty"` // AllowEmptyValue 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 `yaml:"allowEmptyValue,omitempty"` // Style 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 string `yaml:"style,omitempty"` // Explode, when true, makes 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 `yaml:"explode,omitempty"` // AllowReserved 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 `yaml:"allowReserved,omitempty"` // Schema defining the type used for the parameter. Schema *Schema `yaml:"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 `yaml:"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]*Example `yaml:"examples,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Param Describes a single operation parameter.
A unique parameter is defined by a combination of a name and location.
name: username in: path description: username to fetch required: true schema: type: string
func (*Param) MarshalJSON ¶
type ParamBuilder ¶
type ParamBuilder struct {
// contains filtered or unexported fields
}
ParamBuilder helps with building an openapi.Param
func (*ParamBuilder) AddExample ¶
func (pb *ParamBuilder) AddExample(name string) *ExampleBuilder
AddExample adds an example to a list of examples.
func (*ParamBuilder) Description ¶
func (pb *ParamBuilder) Description(description string) *ParamBuilder
Description sets the description of the param
func (*ParamBuilder) Example ¶
func (pb *ParamBuilder) Example(example string) *ParamBuilder
Example sets the example for the param. If you want to add multiple examples, call AddExample() instead.
func (*ParamBuilder) Explode ¶
func (pb *ParamBuilder) Explode(explode bool) *ParamBuilder
Explode explodes
func (*ParamBuilder) In ¶
func (pb *ParamBuilder) In(in string) *ParamBuilder
In can be "query", "path" or "cookie". This should already be set when creating the param and is only here for a manual override.
func (*ParamBuilder) Required ¶
func (pb *ParamBuilder) Required(required bool) *ParamBuilder
Required sets the param as required
func (*ParamBuilder) Style ¶
func (pb *ParamBuilder) Style(style string) *ParamBuilder
Style sets the style of the param. See https://swagger.io/docs/specification/serialization/
type PathBuffer ¶
type PathBuffer struct {
// contains filtered or unexported fields
}
PathBuffer is a low-allocation helper for building a path string like `foo.bar.baz`. It is not goroutine-safe. Combined with `sync.Pool` it can result in zero allocations, and is used for validation. It is significantly better than `strings.Builder` and `bytes.Buffer` for this use case.
Path buffers can be converted to strings for use in responses or printing using either the `pb.String()` or `pb.With("field")` methods.
pb := NewPathBuffer([]byte{}, 0) pb.Push("foo") // foo pb.PushIndex(1) // foo[1] pb.Push("bar") // foo[1].bar pb.Pop() // foo[1] pb.Pop() // foo
func NewPathBuffer ¶
func NewPathBuffer(buf []byte, offset int) *PathBuffer
NewPathBuffer creates a new path buffer given an existing byte slice. Tip: using `sync.Pool` can significantly reduce buffer allocations.
pb := NewPathBuffer([]byte{}, 0) pb.Push("foo")
func (*PathBuffer) Bytes ¶
func (b *PathBuffer) Bytes() []byte
Bytes returns the underlying slice of bytes of the path.
func (*PathBuffer) Pop ¶
func (b *PathBuffer) Pop()
Pop the latest entry off the path.
pb.Push("foo") // foo pb.PushIndex(1) // foo[1] pb.Push("bar") // foo[1].bar pb.Pop() // foo[1] pb.Pop() // foo
func (*PathBuffer) Push ¶
func (b *PathBuffer) Push(s string)
Push an entry onto the path, adding a `.` separator as needed.
pb.Push("foo") // foo pb.Push("bar") // foo.bar
func (*PathBuffer) PushIndex ¶
func (b *PathBuffer) PushIndex(i int)
PushIndex pushes an entry onto the path surrounded by `[` and `]`.
pb.Push("foo") // foo pb.PushIndex(1) // foo[1]
func (*PathBuffer) Reset ¶
func (b *PathBuffer) Reset()
Reset the path buffer to empty, keeping and reusing the underlying bytes.
func (*PathBuffer) String ¶
func (b *PathBuffer) String() string
String converts the path buffer to a string.
func (*PathBuffer) With ¶
func (b *PathBuffer) With(s string) string
With is shorthand for push, convert to string, and pop. This is useful when you want the location of a field given a path buffer as a prefix.
pb.Push("foo") pb.With("bar") // returns foo.bar
type PathItem ¶
type PathItem struct { // Ref is a reference to another example. This field is mutually exclusive // with the other fields. Ref string `yaml:"$ref,omitempty"` // Summary is an optional, string summary, intended to apply to all operations // in this path. Summary string `yaml:"summary,omitempty"` // Description is an optional, string description, intended to apply to all // operations in this path. CommonMark syntax MAY be used for rich text // representation. Description string `yaml:"description,omitempty"` // Get is a definition of a GET operation on this path. Get *Operation `yaml:"get,omitempty"` // Put is a definition of a PUT operation on this path. Put *Operation `yaml:"put,omitempty"` // Post is a definition of a POST operation on this path. Post *Operation `yaml:"post,omitempty"` // Delete is a definition of a DELETE operation on this path. Delete *Operation `yaml:"delete,omitempty"` // Options is a definition of a OPTIONS operation on this path. Options *Operation `yaml:"options,omitempty"` // Head is a definition of a HEAD operation on this path. Head *Operation `yaml:"head,omitempty"` // Patch is a definition of a PATCH operation on this path. Patch *Operation `yaml:"patch,omitempty"` // Trace is a definition of a TRACE operation on this path. Trace *Operation `yaml:"trace,omitempty"` // Servers is an alternative server array to service all operations in this // path. Servers []*Server `yaml:"servers,omitempty"` // Parameters is 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 []*Param `yaml:"parameters,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
PathItem 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.
get: description: Returns pets based on ID summary: Find pets by ID operationId: getPetsById responses: '200': description: pet response content: '*/*' : schema: type: array items: $ref: '#/components/schemas/Pet' default: description: error payload content: 'text/html': schema: $ref: '#/components/schemas/ErrorModel' parameters: - name: id in: path description: ID of pet to use required: true schema: type: array items: type: string style: simple
func (*PathItem) MarshalJSON ¶
type Registry ¶
type Registry interface { Schema(t reflect.Type, allowRef bool, hint string) *Schema SchemaFromRef(ref string) *Schema TypeFromRef(ref string) reflect.Type Map() map[string]*Schema RegisterTypeAlias(t reflect.Type, alias reflect.Type) }
Registry creates and stores schemas and their references, and supports marshalling to JSON/YAML for use as an OpenAPI #/components/schemas object. Behavior is implementation-dependent, but the design allows for recursive schemas to exist while being flexible enough to support other use cases like only inline objects (no refs) or always using refs for structs.
type RequestBody ¶
type RequestBody struct { // Ref is a reference to another example. This field is mutually exclusive // with the other fields. Ref string `yaml:"$ref,omitempty"` // Description of the request body. This could contain examples of use. // CommonMark syntax MAY be used for rich text representation. Description string `yaml:"description,omitempty"` // Content is 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 map[string]*MediaType `yaml:"content"` // Required Determines if the request body is required in the request. // Defaults to false. Required bool `yaml:"required,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
RequestBody describes a single request body.
description: user to add to the system content: 'application/json': schema: $ref: '#/components/schemas/User' examples: user: summary: User Example externalValue: 'https://foo.bar/examples/user-example.json'
func (*RequestBody) MarshalJSON ¶
func (r *RequestBody) MarshalJSON() ([]byte, error)
type RequestBodyBuilder ¶
type RequestBodyBuilder struct {
// contains filtered or unexported fields
}
func (*RequestBodyBuilder) AddExample ¶
func (rbb *RequestBodyBuilder) AddExample(example string) *ExampleBuilder
AddExample adds an example for the body
func (*RequestBodyBuilder) Description ¶
func (rbb *RequestBodyBuilder) Description(description string) *RequestBodyBuilder
Description sets the Description for the RequestBody
func (*RequestBodyBuilder) Example ¶
func (rbb *RequestBodyBuilder) Example(example string) *RequestBodyBuilder
Example sets the example for the body
func (*RequestBodyBuilder) Required ¶
func (rbb *RequestBodyBuilder) Required(required bool) *RequestBodyBuilder
Required makes the Body required for the Request. By default when you call Body() it is already set to true
type RequestBuilder ¶
type RequestBuilder struct {
// contains filtered or unexported fields
}
RequestBuilder helps build a Request
func (*RequestBuilder) Body ¶
func (rb *RequestBuilder) Body(f any) *RequestBodyBuilder
Body sets the RequestBody
func (*RequestBuilder) ContentType ¶
func (rb *RequestBuilder) ContentType(contentType string) *RequestBuilder
ContentType sets the content type of the Request for the next Body() call
func (*RequestBuilder) CookieParam ¶
func (rb *RequestBuilder) CookieParam(name string, f any) *ParamBuilder
CookieParam adds a cookie param
func (*RequestBuilder) DefaultContentType ¶
func (rb *RequestBuilder) DefaultContentType(contentType string) *RequestBuilder
DefaultContentType sets the content type for all Body() calls
func (*RequestBuilder) Param ¶
func (rb *RequestBuilder) Param(in string, name string, f any) *ParamBuilder
Param adds a param. in can be "path", "query", or "cookie". See helper functions QueryParam(), PathParam() and CookieParam() for a shorthand version
func (*RequestBuilder) PathParam ¶
func (rb *RequestBuilder) PathParam(name string, f any) *ParamBuilder
PathParam adds a path param
func (*RequestBuilder) QueryParam ¶
func (rb *RequestBuilder) QueryParam(name string, f any) *ParamBuilder
QueryParam adds a query param
type Response ¶
type Response struct { // Ref is a reference to another example. This field is mutually exclusive // with the other fields. Ref string `yaml:"$ref,omitempty"` // Description is REQUIRED. A description of the response. CommonMark syntax // MAY be used for rich text representation. Description string `yaml:"description,omitempty"` // Headers 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 map[string]*Param `yaml:"headers,omitempty"` // Content is 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 map[string]*MediaType `yaml:"content,omitempty"` // Links is 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 map[string]*Link `yaml:"links,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Response describes a single response from an API Operation, including design-time, static links to operations based on the response.
description: A complex object array response content: application/json: schema: type: array items: $ref: '#/components/schemas/VeryComplexType'
func (*Response) MarshalJSON ¶
type ResponseBuilder ¶
type ResponseBuilder struct {
// contains filtered or unexported fields
}
func (*ResponseBuilder) Body ¶
func (rb *ResponseBuilder) Body(f any) *MediaTypeBuilder
Body adds a body. f is the type that is used for the body's schema. f can be a struct, slice, map, or a basic type. For basic types, you can use our helper methods such as openapi.IntType, openapi.StringType, openapi.UintType, etc. (see types.go for all basic types.)
func (*ResponseBuilder) ContentType ¶
func (rb *ResponseBuilder) ContentType(contentType string) *ResponseBuilder
ContentType applies this content type to the next Body() call. This only applies to the next Body() call and any subsequent calls to Body() will default to DefaultContentType(). If you want to change the default content type for all Body() calls, call DefaultContentType() then call Body() without using ContentType()
func (*ResponseBuilder) DefaultContentType ¶
func (rb *ResponseBuilder) DefaultContentType(contentType string) *ResponseBuilder
DefaultContentType sets the default content type of the Response. By default, the content type is application/json
func (*ResponseBuilder) Header ¶
func (rb *ResponseBuilder) Header(name string, f any) *ParamBuilder
Header adds a Header.
func (*ResponseBuilder) Link ¶
func (rb *ResponseBuilder) Link(name string) *LinkBuilder
Link adds a link to the response.
type Schema ¶
type Schema struct { Type string `yaml:"type,omitempty"` Nullable bool `yaml:"-"` Title string `yaml:"title,omitempty"` Description string `yaml:"description,omitempty"` Ref string `yaml:"$ref,omitempty"` Format string `yaml:"format,omitempty"` ContentEncoding string `yaml:"contentEncoding,omitempty"` Default any `yaml:"default,omitempty"` Examples []any `yaml:"examples,omitempty"` Items *Schema `yaml:"items,omitempty"` AdditionalProperties any `yaml:"additionalProperties,omitempty"` Properties map[string]*Schema `yaml:"properties,omitempty"` Enum []any `yaml:"enum,omitempty"` Minimum *float64 `yaml:"minimum,omitempty"` ExclusiveMinimum *float64 `yaml:"exclusiveMinimum,omitempty"` Maximum *float64 `yaml:"maximum,omitempty"` ExclusiveMaximum *float64 `yaml:"exclusiveMaximum,omitempty"` MultipleOf *float64 `yaml:"multipleOf,omitempty"` MinLength *int `yaml:"minLength,omitempty"` MaxLength *int `yaml:"maxLength,omitempty"` Pattern string `yaml:"pattern,omitempty"` PatternDescription string `yaml:"patternDescription,omitempty"` MinItems *int `yaml:"minItems,omitempty"` MaxItems *int `yaml:"maxItems,omitempty"` UniqueItems bool `yaml:"uniqueItems,omitempty"` Required []string `yaml:"required,omitempty"` MinProperties *int `yaml:"minProperties,omitempty"` MaxProperties *int `yaml:"maxProperties,omitempty"` ReadOnly bool `yaml:"readOnly,omitempty"` WriteOnly bool `yaml:"writeOnly,omitempty"` Deprecated bool `yaml:"deprecated,omitempty"` Extensions map[string]any `yaml:",inline"` DependentRequired map[string][]string `yaml:"dependentRequired,omitempty"` OneOf []*Schema `yaml:"oneOf,omitempty"` AnyOf []*Schema `yaml:"anyOf,omitempty"` AllOf []*Schema `yaml:"allOf,omitempty"` Not *Schema `yaml:"not,omitempty"` // contains filtered or unexported fields }
Schema represents a JSON Schema compatible with OpenAPI 3.1. It is extensible with your own custom properties. It supports a subset of the full JSON Schema spec, designed specifically for use with Go structs and to enable fast zero or near-zero allocation happy-path validation for incoming requests.
Typically you will use a registry and `openapi.SchemaFromType` to generate schemas for your types. You can then use `openapi.Validate` to validate incoming requests.
// Create a registry and register a type. registry := openapi.NewMapRegistry("#/prefix", openapi.DefaultSchemaNamer) schema := openapi.SchemaFromType(registry, reflect.TypeOf(MyType{}))
Note that the registry may create references for your types.
func SchemaFromField ¶
func SchemaFromField(registry Registry, f reflect.StructField, hint string) *Schema
SchemaFromField generates a schema for a given struct field. If the field is a struct (or slice/map of structs) then the registry is used to potentially get a reference to that type.
This is used by `openapi.SchemaFromType` when it encounters a struct, and is used to generate schemas for path/query/header parameters.
func SchemaFromType ¶
SchemaFromType returns a schema for a given type, using the registry to possibly create references for nested structs. The schema that is returned can then be passed to `openapi.Validate` to efficiently validate incoming requests.
// Create a registry and register a type. registry := openapi.NewMapRegistry("#/prefix", openapi.DefaultSchemaNamer) schema := openapi.SchemaFromType(registry, reflect.TypeOf(MyType{}))
func (*Schema) MarshalJSON ¶
MarshalJSON marshals the schema into JSON, respecting the `Extensions` map to marshal extensions inline.
func (*Schema) PrecomputeMessages ¶
func (s *Schema) PrecomputeMessages()
PrecomputeMessages tries to precompute as many validation error messages as possible so that new strings aren't allocated during request validation.
type SchemaProvider ¶
SchemaProvider is an interface that can be implemented by types to provide a custom schema for themselves, overriding the built-in schema generation. This can be used by custom types with their own special serialization rules.
type SecurityScheme ¶
type SecurityScheme struct { // Type is REQUIRED. The type of the security scheme. Valid values are // "apiKey", "http", "mutualTLS", "oauth2", "openIdConnect". Type string `yaml:"type"` // Description for security scheme. CommonMark syntax MAY be used for rich // text representation. Description string `yaml:"description,omitempty"` // Name is REQUIRED. The name of the header, query or cookie parameter to be // used. Name string `yaml:"name,omitempty"` // In is REQUIRED. The location of the API key. Valid values are "query", // "header" or "cookie". In string `yaml:"in,omitempty"` // Scheme is REQUIRED. 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 `yaml:"scheme,omitempty"` // BearerFormat is 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 `yaml:"bearerFormat,omitempty"` // Flows is REQUIRED. An object containing configuration information for the // flow types supported. Flows *OAuthFlows `yaml:"flows,omitempty"` // OpenIDConnectURL is REQUIRED. OpenId Connect URL to discover OAuth2 // configuration values. This MUST be in the form of a URL. The OpenID Connect // standard requires the use of TLS. OpenIDConnectURL string `yaml:"openIdConnectUrl,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
SecurityScheme 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), mutual TLS (use of a client certificate), OAuth2’s common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749], and OpenID Connect Discovery. Please note that as of 2020, the implicit flow is about to be deprecated by OAuth 2.0 Security Best Current Practice. Recommended for most use case is Authorization Code Grant flow with PKCE.
type: http scheme: bearer bearerFormat: JWT
func (*SecurityScheme) MarshalJSON ¶
func (s *SecurityScheme) MarshalJSON() ([]byte, error)
type Server ¶
type Server struct { // 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 `yaml:"url"` // Description of the host designated by the URL. CommonMark syntax MAY be used for rich text representation. Description string `yaml:"description,omitempty"` // Variables map between a variable name and its value. The value is used for substitution in the server’s URL template. Variables map[string]*ServerVariable `yaml:"variables,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Server URL, optionally with variables.
servers: - url: https://development.gigantic-server.com/v1 description: Development server - url: https://staging.gigantic-server.com/v1 description: Staging server - url: https://api.gigantic-server.com/v1 description: Production server
func (*Server) MarshalJSON ¶
type ServerBuilder ¶
type ServerBuilder struct {
// contains filtered or unexported fields
}
ServerBuilder helps with building a Server
func (*ServerBuilder) AddVariable ¶
func (sb *ServerBuilder) AddVariable(name string) *ServerVariableBuilder
AddVariable adds a variable to the server.
func (*ServerBuilder) Description ¶
func (sb *ServerBuilder) Description(description string) *ServerBuilder
Description sets the server description
func (*ServerBuilder) URL ¶
func (sb *ServerBuilder) URL(url string) *ServerBuilder
URL sets the server URL
type ServerVariable ¶
type ServerVariable struct { // Enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty. Enum []string `yaml:"enum,omitempty"` // Default value to use for substitution, which SHALL be sent if an alternate value is not supplied. Default string `yaml:"default"` // Description for the server variable. CommonMark syntax MAY be used for rich text representation. Description string `yaml:"description,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
ServerVariable for server URL template substitution.
func (*ServerVariable) MarshalJSON ¶
func (v *ServerVariable) MarshalJSON() ([]byte, error)
type ServerVariableBuilder ¶
type ServerVariableBuilder struct {
// contains filtered or unexported fields
}
ServerVariableBuilder helps build a server variable
func (*ServerVariableBuilder) Default ¶
func (svb *ServerVariableBuilder) Default(value string) *ServerVariableBuilder
Default sets the default value for the variable
func (*ServerVariableBuilder) Description ¶
func (svb *ServerVariableBuilder) Description(description string) *ServerVariableBuilder
Description sets the description for the variable
func (*ServerVariableBuilder) Enum ¶
func (svb *ServerVariableBuilder) Enum(enum []string) *ServerVariableBuilder
Enum sets the enum for the variable
type Tag ¶
type Tag struct { // Name is REQUIRED. The name of the tag. Name string `yaml:"name"` // Description for the tag. CommonMark syntax MAY be used for rich text // representation. Description string `yaml:"description,omitempty"` // ExternalDocs is additional external documentation for this tag. ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"` // Extensions (user-defined properties), if any. Values in this map will // be marshalled as siblings of the other properties above. Extensions map[string]any `yaml:",inline"` }
Tag 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) MarshalJSON ¶
type ValidateMode ¶
type ValidateMode int
ValidateMode describes the direction of validation (server -> client or client -> server). It impacts things like how read-only or write-only fields are handled.
const ( // ModeReadFromServer is a read mode (response output) that may ignore or // reject write-only fields that are non-zero, as these write-only fields // are meant to be sent by the client. ModeReadFromServer ValidateMode = iota // ModeWriteToServer is a write mode (request input) that may ignore or // reject read-only fields that are non-zero, as these are owned by the // server and the client should not try to modify them. ModeWriteToServer )
type ValidateResult ¶
type ValidateResult struct {
Errors []error
}
ValidateResult tracks validation errors. It is safe to use for multiple validations as long as `Reset()` is called between uses.
func (*ValidateResult) Add ¶
func (r *ValidateResult) Add(path *PathBuffer, v any, msg string)
Add an error to the validation result at the given path and with the given value.
func (*ValidateResult) Addf ¶
func (r *ValidateResult) Addf(path *PathBuffer, v any, format string, args ...any)
Addf adds an error to the validation result at the given path and with the given value, allowing for fmt.Printf-style formatting.
func (*ValidateResult) Reset ¶
func (r *ValidateResult) Reset()
Reset the validation error so it can be used again.