Documentation
¶
Index ¶
- Constants
- Variables
- func DefaultFormats() map[string]Format
- func Delete[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), ...)
- func ErrorWithHeaders(err error, headers http.Header) error
- func FindBodyField(structMeta *schema.StructMetadata) *schema.FieldMetadata
- func Get[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), ...)
- func GetRouterParams(r *http.Request) map[string]string
- func Head[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), ...)
- func NewMetadata() *schema.Metadata
- func Patch[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), ...)
- func Post[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), ...)
- func PrefixModifier(prefixes []string) func(o *BaseRoute, next func(*BaseRoute))
- func Put[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), ...)
- func Register[I, O any](api API, route BaseRoute, handler func(context.Context, *I) (*O, error)) error
- func Secure(opts ...SecurityOption) func(*BaseRoute)
- func WriteErr(api API, r *http.Request, w http.ResponseWriter, status int, msg string, ...)
- type API
- type Adapter
- type BaseRoute
- type Codec
- type Components
- type Config
- type Contact
- type ContentTypeProvider
- type Discriminator
- type Encoding
- type ErrorDetail
- type ErrorDetailer
- type ErrorModel
- type Example
- type ExternalDocs
- type Format
- type Group
- func (g *Group) Adapter() Adapter
- func (g *Group) Middlewares() Middlewares
- func (g *Group) ModifyOperation(route *BaseRoute, next func(*BaseRoute))
- func (g *Group) Transform(r *http.Request, status int, v any) (any, error)
- func (g *Group) UseMiddleware(middlewares ...Middleware)
- func (g *Group) UseModifier(modifier func(o *BaseRoute, next func(*BaseRoute)))
- func (g *Group) UsePermissions(perms ...string)
- func (g *Group) UseResource(resource string)
- func (g *Group) UseRoles(roles ...string)
- func (g *Group) UseSimpleModifier(modifier func(o *BaseRoute))
- func (g *Group) UseTransformer(transformers ...Transformer)
- func (g *Group) WithSecurity(security *RouteSecurity)
- type Header
- type HeadersError
- type Info
- type License
- type Link
- type MediaType
- type Middleware
- type Middlewares
- type OAuthFlow
- type OAuthFlows
- type OpenAPI
- type Operation
- type Option
- func WithCodec(codec *schema.Codec) Option
- func WithConfig(config *Config) Option
- func WithDefaultFormat(format string) Option
- func WithFormat(contentType string, format Format) Option
- func WithFormats(formats map[string]Format) Option
- func WithFormatsReplace(formats map[string]Format) Option
- func WithMetadata(metadata *schema.Metadata) Option
- func WithOpenAPI(openAPI *OpenAPI) Option
- func WithValidator(validator Validator) Option
- type Param
- type PathItem
- type PlaygroundValidator
- type RequestBody
- type Response
- type RouteSecurity
- type RouteSecurityContext
- type Schema
- type SecurityOption
- func Action(action string) SecurityOption
- func Permissions(perms ...string) SecurityOption
- func Resource(resource string) SecurityOption
- func ResourceFromParams(fn func(params map[string]string) string) SecurityOption
- func ResourceFromRequest(fn func(r *http.Request) string) SecurityOption
- func Roles(roles ...string) SecurityOption
- type SecurityScheme
- type Server
- type ServerVariable
- type StatusError
- func Error400BadRequest(msg string, errs ...error) StatusError
- func Error401Unauthorized(msg string, errs ...error) StatusError
- func Error403Forbidden(msg string, errs ...error) StatusError
- func Error404NotFound(msg string, errs ...error) StatusError
- func Error405MethodNotAllowed(msg string, errs ...error) StatusError
- func Error406NotAcceptable(msg string, errs ...error) StatusError
- func Error409Conflict(msg string, errs ...error) StatusError
- func Error410Gone(msg string, errs ...error) StatusError
- func Error412PreconditionFailed(msg string, errs ...error) StatusError
- func Error415UnsupportedMediaType(msg string, errs ...error) StatusError
- func Error422UnprocessableEntity(msg string, errs ...error) StatusError
- func Error429TooManyRequests(msg string, errs ...error) StatusError
- func Error500InternalServerError(msg string, errs ...error) StatusError
- func Error501NotImplemented(msg string, errs ...error) StatusError
- func Error502BadGateway(msg string, errs ...error) StatusError
- func Error503ServiceUnavailable(msg string, errs ...error) StatusError
- func Error504GatewayTimeout(msg string, errs ...error) StatusError
- func Status304NotModified() StatusError
- type StatusProvider
- type Tag
- type Transformer
- type Validator
Constants ¶
const ( TypeBoolean = "boolean" TypeInteger = "integer" TypeNumber = "number" TypeString = "string" TypeArray = "array" TypeObject = "object" )
JSON Schema type constants.
const DefaultBodyReadTimeout = 5 * time.Second
DefaultBodyReadTimeout is the default timeout for reading request bodies (5 seconds).
const DefaultMaxBodyBytes int64 = 1024 * 1024
DefaultMaxBodyBytes is the default maximum request body size (1MB).
Variables ¶
var DefaultArrayNullable = true
DefaultArrayNullable controls whether arrays are nullable by default. Set this to `false` to make arrays non-nullable by default, but be aware that any `nil` slice will still encode as `null` in JSON. See also: https://pkg.go.dev/encoding/json#Marshal.
var NewError = func(status int, msg string, errs ...error) StatusError { details := make([]*ErrorDetail, 0, len(errs)) for i := range len(errs) { if errs[i] == nil { continue } if converted, ok := errs[i].(ErrorDetailer); ok { details = append(details, converted.ErrorDetail()) } else { details = append(details, &ErrorDetail{Message: errs[i].Error()}) } } title := http.StatusText(status) if title == "" { title = "Error" } return &ErrorModel{ Status: status, Title: title, Detail: msg, Errors: details, } }
NewError creates a new instance of an error model with the given status code, message, and optional error details. If the error details implement the `ErrorDetailer` interface, the error details will be used. Otherwise, the error string will be used as the message.
Replace this function to use your own error type. Example:
type MyDetail struct {
Message string `json:"message"`
Location string `json:"location"`
}
type MyError struct {
status int
Message string `json:"message"`
Errors []error `json:"errors"`
}
func (e *MyError) Error() string {
return e.Message
}
func (e *MyError) GetStatus() int {
return e.status
}
zorya.NewError = func(status int, msg string, errs ...error) StatusError {
return &MyError{
status: status,
Message: msg,
Errors: errs,
}
}
Functions ¶
func DefaultFormats ¶
DefaultFormats returns the standard format set with JSON and CBOR.
func Delete ¶
func Delete[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), options ...func(*BaseRoute))
Delete registers a DELETE route handler. Panics on errors since route registration happens during startup and errors represent programming/configuration mistakes.
func ErrorWithHeaders ¶
ErrorWithHeaders wraps an error with additional headers to be sent to the client. This is useful for e.g. caching, rate limiting, or other metadata.
func FindBodyField ¶
func FindBodyField(structMeta *schema.StructMetadata) *schema.FieldMetadata
FindBodyField finds the field with "body" tag in the struct metadata. If none, falls back to a field named "Body" with type func(http.ResponseWriter) error (streaming). Returns nil if no body field is found.
func Get ¶
func Get[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), options ...func(*BaseRoute))
Get registers a GET route handler. Panics on errors since route registration happens during startup and errors represent programming/configuration mistakes.
func GetRouterParams ¶
GetRouterParams retrieves router parameters from the request context. Returns nil if no parameters are available.
Example:
params := zorya.GetRouterParams(r) orgID := params["orgId"]
func Head ¶
func Head[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), options ...func(*BaseRoute))
Head registers a HEAD route handler. Panics on errors since route registration happens during startup and errors represent programming/configuration mistakes.
func NewMetadata ¶
NewMetadata returns a schema.Metadata configured with Zorya's tag parsers (schema, body, openapi, validate, default, requires).
func Patch ¶
func Patch[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), options ...func(*BaseRoute))
Patch registers a PATCH route handler. Panics on errors since route registration happens during startup and errors represent programming/configuration mistakes.
func Post ¶
func Post[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), options ...func(*BaseRoute))
Post registers a POST route handler. Panics on errors since route registration happens during startup and errors represent programming/configuration mistakes.
func PrefixModifier ¶
PrefixModifier provides a fan-out to register one or more operations with the given prefix for every one operation added to a group.
func Put ¶
func Put[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), options ...func(*BaseRoute))
Put registers a PUT route handler. Panics on errors since route registration happens during startup and errors represent programming/configuration mistakes.
func Secure ¶
func Secure(opts ...SecurityOption) func(*BaseRoute)
Secure wraps security options and automatically injects metadata middleware. The metadata middleware resolves resource templates and stores requirements in context. Enforcement is done by the global security middleware (registered via api.UseMiddleware).
Secure() requires at least one security option (Roles, Permissions, or Resource). Routes without Secure() are public by default.
Usage:
zorya.Get(api, "/admin/users", handler,
zorya.Secure(
zorya.Roles("admin"),
),
)
zorya.Get(api, "/orgs/{orgId}/projects", handler,
zorya.Secure(
zorya.Roles("member"),
zorya.ResourceFromParams(func(params map[string]string) string {
return "orgs/" + params["orgId"] + "/projects"
}),
),
)
func WriteErr ¶
func WriteErr(api API, r *http.Request, w http.ResponseWriter, status int, msg string, errs ...error)
WriteErr writes an error response with the given request and response writer. It can be called in two ways:
- With status and message: WriteErr(api, r, w, status, msg, errs...)
- With an existing error: WriteErr(api, r, w, 0, "", err) where err is the error to write
If status is 0 and msg is empty, the first error in errs is used as the main error. Otherwise, a new error is created using NewError(status, msg, errs...). The error is marshaled using the API's content negotiation methods.
Types ¶
type API ¶
type API interface {
// Adapter returns the router adapter for this API, providing a generic
// interface to get request information and write responses.
Adapter() Adapter
// Middlewares returns a slice of middleware handler functions that will be
// run for all operations. Middleware are run in the order they are added.
Middlewares() Middlewares
// UseMiddleware adds one or more standard Go middleware functions to the API.
// Middleware functions take an http.Handler and return an http.Handler.
UseMiddleware(middlewares ...Middleware)
// Codec returns the schema codec used for request decoding and response encoding.
Codec() Codec
// Metadata returns the schema metadata instance used by this API.
Metadata() *schema.Metadata
// Negotiate returns the best content type for the response based on the
// Accept header. If no match is found, returns the default format.
Negotiate(accept string) (string, error)
// Marshal writes the value to the writer using the format for the given
// content type. Supports plus-segment matching (e.g., application/vnd.api+json).
// If marshaling fails, it falls back to plain text representation.
Marshal(w io.Writer, contentType string, v any)
// Validator returns the configured validator, or nil if validation is disabled.
Validator() Validator
// Transform runs all transformers on the response value.
// Called automatically during response serialization.
Transform(r *http.Request, status int, v any) (any, error)
// UseTransformer adds one or more transformer functions that will be
// run on all responses.
UseTransformer(transformers ...Transformer)
// OpenAPI returns the OpenAPI spec for this API. You may edit this spec
// until the server starts.
OpenAPI() *OpenAPI
// contains filtered or unexported methods
}
API is the core interface for a Zorya API. It provides request/response handling, content negotiation, validation, and OpenAPI spec generation.
func NewAPI ¶
NewAPI creates a new API instance with the given adapter and options. The adapter is required; all other configuration is optional.
Example:
api := zorya.NewAPI(adapter)
api := zorya.NewAPI(adapter, zorya.WithValidator(validator))
api := zorya.NewAPI(adapter, zorya.WithFormat("application/xml", xmlFormat))
api := zorya.NewAPI(adapter, zorya.WithFormats(customFormats))
api := zorya.NewAPI(adapter, zorya.WithFormatsReplace(formats)) // Replace all formats
type Adapter ¶
type Adapter interface {
// Handle registers a route with a standard http.HandlerFunc.
Handle(route *BaseRoute, handler http.HandlerFunc)
// ExtractRouterParams extracts router parameters from the request.
ExtractRouterParams(r *http.Request, route *BaseRoute) map[string]string
// ServeHTTP makes the adapter compatible with http.Handler interface.
// This allows the adapter to be used directly with http.ListenAndServe,
// mounted as a sub-handler in other routers, or used in testing scenarios
// (e.g., with httptest.NewRecorder).
ServeHTTP(http.ResponseWriter, *http.Request)
}
Adapter is an interface that allows the API to be used with different HTTP routers and frameworks. It is designed to work with the standard library `http.Request` and `http.ResponseWriter` types as well as types like `gin.Context` or `fiber.Ctx` that provide both request and response functionality in one place, by using the `zorya.Context` interface which abstracts away those router-specific differences.
type BaseRoute ¶
type BaseRoute struct {
// OpenAPI operation
Operation *Operation
// HTTP method (GET, POST, PUT, PATCH, DELETE)
Method string
// URL path. Will be prefixed by the base path of the server and the group path if any
Path string
// DefaultStatus is the default HTTP status code for this operation. It will
// be set to 200 or 204 if not specified, depending on whether the handler
// returns a response body.
DefaultStatus int
// Middlewares is a list of middleware functions to run before the handler.
// This is useful for adding custom logic to operations, such as logging,
// authentication, or rate limiting.
Middlewares Middlewares
// BodyReadTimeout sets a deadline for reading the request body.
// If > 0, sets read deadline to now + timeout.
// If == 0, uses DefaultBodyReadTimeout (5 seconds).
// If < 0, disables any deadline (no timeout).
BodyReadTimeout time.Duration
// MaxBodyBytes limits the size of the request body in bytes.
// If > 0, enforces the specified limit.
// If == 0, uses DefaultMaxBodyBytes (1MB).
// If < 0, disables the limit (no size restriction).
MaxBodyBytes int64
// Errors is a list of HTTP status codes that the handler may return. If
// not specified, then a default error response is added to the OpenAPI.
// This is a convenience for handlers that return a fixed set of errors
// where you do not wish to provide each one as an OpenAPI response object.
// Each error specified here is expanded into a response object with the
// schema generated from the type returned by `NewError()`.
Errors []int
// Security holds authorization requirements for this route.
// Routes without Security are public by default (anonymous access allowed).
// Adding any security requirement makes the route protected.
Security *RouteSecurity
}
BaseRoute is the base struct for all routes in Zorya. It contains the OpenAPI operation and other metadata.
type Codec ¶
type Codec interface {
// DecodeRequest decodes an HTTP request into the provided struct.
DecodeRequest(request *http.Request, routerParams map[string]string, result any) error
}
Codec is an interface that allows to map request and router parameters into Go structures.
type Components ¶
type Components struct {
// Schemas is an object to hold reusable Schema Objects.
Schemas map[string]*Schema
// Responses is an object to hold reusable Response Objects.
Responses map[string]*Response
// Parameters is an object to hold reusable Parameter Objects.
Parameters map[string]*Param
// Examples is an object to hold reusable Example Objects.
Examples map[string]*Example
// RequestBodies is an object to hold reusable Request Body Objects.
RequestBodies map[string]*RequestBody
// Headers is an object to hold reusable Header Objects.
Headers map[string]*Header
// SecuritySchemes is an object to hold reusable Security Scheme Objects.
SecuritySchemes map[string]*SecurityScheme
// Links is an object to hold reusable Link Objects.
Links map[string]*Link
// Callbacks is an object to hold reusable Callback Objects.
Callbacks map[string]*PathItem
// PathItems is an object to hold reusable Path Item Objects.
PathItems map[string]*PathItem
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 Config ¶
type Config struct {
// OpenAPIPath is the exact path to the OpenAPI spec endpoint.
// The path is used as-is, with no automatic suffix or extension handling.
OpenAPIPath string
// DocsPath is the path to the API documentation. If set to `/docs` it will
// allow clients to get `/docs` to view the documentation in a browser. If
// you wish to provide your own documentation renderer, you can leave this
// blank and attach it directly to the router or adapter.
DocsPath string
// SchemasPath is the path to the API schemas. If set to `/schemas` it will
// allow clients to get `/schemas/{schema}` to view the schema in a browser
// or for use in editors like VSCode to provide autocomplete & validation.
SchemasPath string
// DefaultFormat specifies the default content type to use when the client
// does not specify one. If unset, the default type will be randomly
// chosen from the keys of `Formats`.
DefaultFormat string
// NoFormatFallback disables the fallback to application/json (if available)
// when the client requests an unknown content type. If set and no format is
// negotiated, then a 406 Not Acceptable response will be returned.
NoFormatFallback bool
}
Config represents a configuration for a new API. See `DefaultConfig()` as a starting point.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a default configuration for a new API. It is a good starting point for creating your own configuration. It supports the JSON format out of the box. The `/openapi.json`, `/docs`, and `/schemas` paths are set up to serve the OpenAPI spec, docs UI, and schemas respectively.
// Create and customize the config (if desired). config := zorya.DefaultConfig() // Create the API using the config. router := adapters.NewChiAdapter() api := zorya.NewAPI(router, zorya.WithConfig(config))
type Contact ¶
type Contact struct {
// Name of the contact person/organization.
Name string
// URL pointing to the contact information.
URL string
// Email address of the contact person/organization.
Email string
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 ContentTypeProvider ¶
ContentTypeProvider allows types to override their content type. For example, ErrorModel implements this to return "application/problem+json".
type Discriminator ¶
type Discriminator struct {
// PropertyName in the payload that will hold the discriminator value.
// REQUIRED.
PropertyName string `json:"propertyName"`
// Mapping object to hold mappings between payload values and schema names or
// references.
Mapping map[string]string `json:"mapping,omitempty"`
}
Discriminator object when request bodies or response payloads may be one of a number of different schemas, 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 document of an alternative schema based on the value associated with it.
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
// 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
// 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
// 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
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 {
// Code is a machine-readable error code (e.g., "required", "email", "min").
// This enables frontend translation and automated error handling.
Code string `json:"code,omitempty"`
// Message is a human-readable explanation of the error (optional).
// Useful for developers, logs, and debugging.
Message string `json:"message,omitempty"`
// 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"`
}
ErrorDetail provides details about a specific error.
func (*ErrorDetail) Error ¶
func (e *ErrorDetail) Error() string
Error returns the error message / satisfies the `error` interface.
func (*ErrorDetail) ErrorDetail ¶
func (e *ErrorDetail) ErrorDetail() *ErrorDetail
ErrorDetail satisfies the `ErrorDetailer` interface.
type ErrorDetailer ¶
type ErrorDetailer interface {
ErrorDetail() *ErrorDetail
}
ErrorDetailer returns error details for responses & debugging. This enables the use of custom error types. See `NewError` for more details.
type ErrorModel ¶
type ErrorModel struct {
// Type is a URI to get more information about the error type.
Type string `json:"type,omitempty"`
// Title provides a short static summary of the problem. Zorya will default this
// to the HTTP response status code text if not present.
Title string `json:"title,omitempty"`
// Status provides the HTTP status code for client convenience. Zorya will
// default this to the response status code if unset. This SHOULD match the
// response status code (though proxies may modify the actual status code).
Status int `json:"status,omitempty"`
// Detail is an explanation specific to this error occurrence.
Detail string `json:"detail,omitempty"`
// Instance is a URI to get more info about this error occurrence.
Instance string `json:"instance,omitempty"`
// Errors provides an optional mechanism of passing additional error details
// as a list.
Errors []*ErrorDetail `json:"errors,omitempty"`
}
ErrorModel defines a basic error message model based on RFC 9457 Problem Details for HTTP APIs (https://datatracker.ietf.org/doc/html/rfc9457). It is augmented with an `errors` field of `ErrorDetail` objects that can help provide exhaustive & descriptive errors.
err := &ErrorModel{
Title: http.StatusText(http.StatusBadRequest),
Status: http.StatusBadRequest,
Detail: "Validation failed",
Errors: []*ErrorDetail{
{
Code: "required",
Message: "expected required property id to be present",
Location: "body.friends[0]",
},
{
Code: "type",
Message: "expected boolean",
Location: "body.friends[1].active",
},
},
}
func (*ErrorModel) Add ¶
func (e *ErrorModel) Add(err error)
Add an error to the `Errors` slice. If passed a struct that satisfies the `ErrorDetailer` interface, then it is used, otherwise the error string is used as the error detail message.
err := &ErrorModel{ /* ... */ }
err.Add(&ErrorDetail{
Code: "type",
Message: "expected boolean",
Location: "body.friends[1].active",
})
func (*ErrorModel) ContentType ¶
func (e *ErrorModel) ContentType(ct string) string
ContentType provides a filter to adjust response content types. This is used to ensure e.g. `application/problem+json` content types defined in RFC 9457 Problem Details for HTTP APIs are used in responses to clients.
func (*ErrorModel) Error ¶
func (e *ErrorModel) Error() string
Error satisfies the `error` interface. It returns the error's detail field.
func (*ErrorModel) GetStatus ¶
func (e *ErrorModel) GetStatus() int
GetStatus returns the HTTP status that should be returned to the client for this error.
type Example ¶
type Example struct {
// Ref is a reference to another example. This field is mutually exclusive
// with the other fields.
Ref string
// Summary is a short summary of the example.
Summary string
// Description is a long description of the example. CommonMark syntax MAY
// be used for rich text representation.
Description string
// 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
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 ExternalDocs ¶
type ExternalDocs struct {
// Description of the target documentation. CommonMark syntax MAY be used for
// rich text representation.
Description string
// URL is REQUIRED. The URL for the target documentation. Value MUST be in the
// format of a URL.
URL string
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 Format ¶
Format defines how to marshal values for a given content type (e.g., application/json).
type Group ¶
type Group struct {
API
// contains filtered or unexported fields
}
Group is a collection of routes that share a common prefix and set of operation modifiers, middlewares, and transformers.
This is useful for grouping related routes together and applying common settings to them. For example, you might create a group for all routes that require authentication.
func NewGroup ¶
NewGroup creates a new group of routes with the given prefixes, if any. A group enables a collection of operations to have the same prefix and share operation modifiers, middlewares, and transformers.
grp := zorya.NewGroup(api, "/v1")
grp.UseMiddleware(authMiddleware)
zorya.Get(grp, "/users", func(ctx context.Context, input *MyInput) (*MyOutput, error) {
// Your code here...
})
func (*Group) Adapter ¶
Adapter returns the group's adapter, which applies group modifiers before delegating to the underlying API adapter.
func (*Group) Middlewares ¶
func (g *Group) Middlewares() Middlewares
Middlewares returns the combined middlewares from the parent API and this group.
func (*Group) ModifyOperation ¶
ModifyOperation runs all operation modifiers in the group on the given route, in the order they were added. This is useful for modifying a route before it is registered with the router.
func (*Group) Transform ¶
Transform runs all transformers in the group on the response, in the order they were added, then chains to the parent API's transformers.
func (*Group) UseMiddleware ¶
func (g *Group) UseMiddleware(middlewares ...Middleware)
UseMiddleware adds one or more standard Go middleware functions to the group. Middleware functions take an http.Handler and return an http.Handler.
func (*Group) UseModifier ¶
UseModifier adds an operation modifier function to the group that will be run on all operations in the group. Use this to modify the operation before it is registered with the router. This behaves similar to middleware in that you should invoke `next` to continue the chain. Skip it to prevent the operation from being registered, and call multiple times for a fan-out effect.
func (*Group) UsePermissions ¶
UsePermissions requires users to have all specified permissions for all routes in the group.
func (*Group) UseResource ¶
UseResource sets the RBAC resource for all routes in the group.
func (*Group) UseRoles ¶
UseRoles requires users to have at least one of the specified roles for all routes in the group.
func (*Group) UseSimpleModifier ¶
UseSimpleModifier adds an operation modifier function to the group that will be run on all operations in the group. Use this to modify the operation before it is registered with the router.
func (*Group) UseTransformer ¶
func (g *Group) UseTransformer(transformers ...Transformer)
UseTransformer adds one or more transformer functions to the group that will be run on all responses in the group.
func (*Group) WithSecurity ¶
func (g *Group) WithSecurity(security *RouteSecurity)
WithSecurity sets security requirements for all routes in the group.
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 HeadersError ¶
HeadersError is an error that has HTTP headers. When returned from an operation handler, these headers are set on the response before sending it to the client. Use `ErrorWithHeaders` to wrap an error like `Error400BadRequest` with additional headers.
type Info ¶
type Info struct {
// Title of the API.
Title string
// Description of the API. CommonMark syntax MAY be used for rich text representation.
Description string
// TermsOfService URL for the API.
TermsOfService string
// Contact information to get support for the API.
Contact *Contact
// License name & link for using the API.
License *License
// Version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).
Version string
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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
// Identifier SPDX license expression for the API. This field is mutually
// exclusive with the URL field.
Identifier string
// URL pointing to the license. This field is mutually exclusive with the
// Identifier field.
URL string
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
License name & link for using the API.
name: Apache 2.0 identifier: Apache-2.0
func (*License) MarshalJSON ¶
type Link ¶
type Link struct {
// Ref is a reference to another example. This field is mutually exclusive
// with the other fields.
Ref string
// 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
// 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
// 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
// RequestBody is a literal value or {expression} to use as a request body
// when calling the target operation.
RequestBody any
// Description of the link. CommonMark syntax MAY be used for rich text representation.
Description string
// Server object to be used by the target operation.
Server *Server
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 MediaType ¶
type MediaType struct {
// Schema defining the content of the request, response, or parameter.
Schema *Schema
// 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
// 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
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 Middleware ¶
Middleware is a standard Go middleware function that takes an http.Handler and returns an http.Handler.
type Middlewares ¶
type Middlewares []Middleware
Middlewares is a list of standard middleware functions that can be attached to an API and will be called for all incoming requests.
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
// 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
// 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
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 OAuthFlows ¶
type OAuthFlows struct {
// Implicit is the configuration for the OAuth Implicit flow.
Implicit *OAuthFlow
// Password is the configuration for the OAuth Resource Owner Password flow.
Password *OAuthFlow
// ClientCredentials is the configuration for the OAuth Client Credentials
// flow. Previously called application in OpenAPI 2.0.
ClientCredentials *OAuthFlow
// AuthorizationCode is the configuration for the OAuth Authorization Code
// flow. Previously called accessCode in OpenAPI 2.0.
AuthorizationCode *OAuthFlow
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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
// Info is REQUIRED. Provides metadata about the API. The metadata MAY be used
// by tooling as required.
Info *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
// 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
// Paths are the available paths and operations for the API.
Paths map[string]*PathItem
// 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
// Components is an element to hold various schemas for the document.
Components *Components
// 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
// 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
// ExternalDocs is additional external documentation.
ExternalDocs *ExternalDocs
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
OpenAPI is the root object of the OpenAPI document.
func DefaultOpenAPI ¶
DefaultOpenAPI returns a new OpenAPI 3.1 document with the given title and version.
func (*OpenAPI) MarshalJSON ¶
type Operation ¶
type Operation struct {
// 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
// Summary is a short summary of what the operation does.
Summary string
// Description is a verbose explanation of the operation behavior. CommonMark
// syntax MAY be used for rich text representation.
Description string
// ExternalDocs describes additional external documentation for this
// operation.
ExternalDocs *ExternalDocs
// 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
// 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
// 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
// Responses is the list of possible responses as they are returned from
// executing this operation.
Responses map[string]*Response
// 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. The Callback
// Object consists of a map of possible request URL expressions to PathItem
// objects describing the request.
//
// callbacks:
// myName:
// '{$request.body#/url}':
// post:
// requestBody:
// description: callback payload
// content:
// application/json:
// schema:
// $ref: '#/components/schemas/SomePayload'
// responses:
// '200':
// description: callback response
Callbacks map[string]map[string]*PathItem
// Deprecated declares this operation to be deprecated. Consumers SHOULD
// refrain from usage of the declared operation. Default value is false.
Deprecated bool
// 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
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 Option ¶
type Option func(*api)
Option configures an API.
func WithCodec ¶
WithCodec sets a custom codec for request/response encoding/decoding. Note: If you use WithCodec, you should also use WithMetadata to ensure the metadata instance matches the codec's metadata.
func WithConfig ¶
WithConfig sets the API configuration (OpenAPI path, docs path, default format, etc.).
func WithDefaultFormat ¶
WithDefaultFormat sets the default content type when Accept header is missing or no match is found.
func WithFormat ¶
WithFormat adds a single format for content negotiation. Multiple calls to WithFormat can be chained to add multiple formats. Formats are merged with default formats, with later formats taking precedence. Default formats are automatically included, so you don't need to add them manually.
func WithFormats ¶
WithFormats sets custom formats for content negotiation. Custom formats are merged with default formats, with custom formats taking precedence. Default formats are automatically included, so you don't need to add them manually.
func WithFormatsReplace ¶
WithFormatsReplace replaces all formats (does not merge with defaults). Use this when you want complete control over supported formats. Default formats are NOT included unless you explicitly add them.
func WithMetadata ¶
WithMetadata sets a custom metadata instance for schema operations.
func WithOpenAPI ¶
WithOpenAPI sets a custom OpenAPI spec for the API. If not set, a default spec is created.
func WithValidator ¶
WithValidator sets a validator for request validation.
type Param ¶
type Param struct {
// Ref is a reference to another example. This field is mutually exclusive
// with the other fields.
Ref string
// 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
// In is REQUIRED. The location of the parameter. Possible values are "query",
// "header", "path" or "cookie".
In string
// Description of the parameter. This could contain examples of use.
// CommonMark syntax MAY be used for rich text representation.
Description string
// 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
// Deprecated specifies that a parameter is deprecated and SHOULD be
// transitioned out of usage. Default value is false.
Deprecated bool
// 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
// 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
// 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
// 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
// Schema defining the type used for the parameter.
Schema *Schema
// 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
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 PathItem ¶
type PathItem struct {
// Ref is a reference to another example. This field is mutually exclusive
// with the other fields.
Ref string
// Summary is an optional, string summary, intended to apply to all operations
// in this path.
Summary string
// 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
// Get is a definition of a GET operation on this path.
Get *Operation
// Put is a definition of a PUT operation on this path.
Put *Operation
// Post is a definition of a POST operation on this path.
Post *Operation
// Delete is a definition of a DELETE operation on this path.
Delete *Operation
// Options is a definition of a OPTIONS operation on this path.
Options *Operation
// Head is a definition of a HEAD operation on this path.
Head *Operation
// Patch is a definition of a PATCH operation on this path.
Patch *Operation
// Trace is a definition of a TRACE operation on this path.
Trace *Operation
// Servers is an alternative server array to service all operations in this
// path.
Servers []*Server
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 PlaygroundValidator ¶
type PlaygroundValidator struct {
// contains filtered or unexported fields
}
PlaygroundValidator adapts go-playground/validator to Zorya's Validator interface.
func NewPlaygroundValidator ¶
func NewPlaygroundValidator(v *validator.Validate) *PlaygroundValidator
NewPlaygroundValidator creates a new validator adapter for go-playground/validator.
func (*PlaygroundValidator) Validate ¶
func (v *PlaygroundValidator) Validate(ctx context.Context, input any, metadata *schema.StructMetadata) []error
Validate validates the input struct using go-playground/validator. Returns validation errors as ErrorDetail objects with code, message, and location.
type RequestBody ¶
type RequestBody struct {
// Ref is a reference to another example. This field is mutually exclusive
// with the other fields.
Ref string
// Description of the request body. This could contain examples of use.
// CommonMark syntax MAY be used for rich text representation.
Description string
// 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
// Required Determines if the request body is required in the request.
// Defaults to false.
Required bool
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 Response ¶
type Response struct {
// Ref is a reference to another example. This field is mutually exclusive
// with the other fields.
Ref string
// Description is REQUIRED. A description of the response. CommonMark syntax
// MAY be used for rich text representation.
Description string
// 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
// 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
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 RouteSecurity ¶
type RouteSecurity struct {
// Roles required (any match grants access)
Roles []string
// Permissions required (all must match)
Permissions []string
// Resource identifier for RBAC (static or template)
Resource string
// ResourceResolver dynamically resolves the resource string at runtime.
// If set, this takes precedence over Resource field.
// Receives the request and path parameters extracted by the router.
ResourceResolver func(r *http.Request, params map[string]string) string
// Action for RBAC
Action string
}
RouteSecurity defines authorization requirements for a route. Routes without RouteSecurity are public by default (anonymous access allowed). Adding any security requirement makes the route protected.
type RouteSecurityContext ¶
type RouteSecurityContext struct {
Roles []string
Permissions []string
Resource string
Action string // Resolved action (explicit or HTTP method fallback)
}
RouteSecurityContext contains fully resolved security requirements It's stored in context by Zorya's security middleware after resolving resources.
func GetRouteSecurityContext ¶
func GetRouteSecurityContext(r *http.Request) *RouteSecurityContext
GetRouteSecurityContext retrieves resolved security metadata from request context.
type Schema ¶
type Schema struct {
Type string
Nullable *bool
Title string
Description string
Ref string
Format string
ContentEncoding string
ContentMediaType string
Default any
Examples []any
Items *Schema
AdditionalProperties any
Properties map[string]*Schema
Enum []any
Const any
Minimum *float64
ExclusiveMinimum *float64
Maximum *float64
ExclusiveMaximum *float64
MultipleOf *float64
MinLength *int
MaxLength *int
Pattern string
PatternDescription string
MinItems *int
MaxItems *int
UniqueItems *bool
Required []string
MinProperties *int
MaxProperties *int
ReadOnly *bool
WriteOnly *bool
Deprecated *bool
Extensions map[string]any
DependentRequired map[string][]string
OneOf []*Schema
AnyOf []*Schema
AllOf []*Schema
Not *Schema
// OpenAPI specific fields
Discriminator *Discriminator
// 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 `Registry.Schema()` to generate schemas for your types.
// Create a registry and register a type.
registry := NewMapRegistry("#/prefix", DefaultSchemaNamer)
schema := registry.Schema(reflect.TypeOf(MyType{}), true, "MyType")
Note that the registry may create references for your types.
func (*Schema) MarshalJSON ¶
MarshalJSON marshals the schema into JSON, respecting the `Extensions` map to marshal extensions inline.
type SecurityOption ¶
type SecurityOption func(*RouteSecurity)
SecurityOption configures security requirements for a route.
func Permissions ¶
func Permissions(perms ...string) SecurityOption
Permissions requires the user to have all specified permissions.
func Resource ¶
func Resource(resource string) SecurityOption
Resource sets a static RBAC resource identifier. For dynamic resources with path parameters, use ResourceFromParams or ResourceFromRequest.
func ResourceFromParams ¶
func ResourceFromParams(fn func(params map[string]string) string) SecurityOption
ResourceFromParams resolves a resource using path parameters. The resolver function receives only the path parameters extracted from the route. This is the recommended approach for most dynamic resource cases.
Example:
zorya.Get(api, "/orgs/{orgId}/projects", handler,
zorya.Secure(
zorya.Roles("member"),
zorya.ResourceFromParams(func(params map[string]string) string {
orgId := params["orgId"]
if !isValidUUID(orgId) {
panic("invalid orgId")
}
return "orgs/" + orgId + "/projects"
}),
),
)
func ResourceFromRequest ¶
func ResourceFromRequest(fn func(r *http.Request) string) SecurityOption
ResourceFromRequest resolves a resource using the full HTTP request. Use this for complex cases that need query parameters, headers, or other request data. For simple path parameter cases, prefer ResourceFromParams.
Example:
zorya.Get(api, "/reports", handler,
zorya.Secure(
zorya.Roles("analyst"),
zorya.ResourceFromRequest(func(r *http.Request) string {
year := r.URL.Query().Get("year")
dept := r.Header.Get("X-Department")
return fmt.Sprintf("reports/%s/%s", dept, year)
}),
),
)
func Roles ¶
func Roles(roles ...string) SecurityOption
Roles requires the user to have at least one of the specified roles.
type SecurityScheme ¶
type SecurityScheme struct {
// Type is REQUIRED. The type of the security scheme. Valid values are
// "apiKey", "http", "mutualTLS", "oauth2", "openIdConnect".
Type string
// Description for security scheme. CommonMark syntax MAY be used for rich
// text representation.
Description string
// Name is REQUIRED. The name of the header, query or cookie parameter to be
// used.
Name string
// In is REQUIRED. The location of the API key. Valid values are "query",
// "header" or "cookie".
In string
// 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.
// See: http://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml
Scheme string
// 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
// Flows is REQUIRED. An object containing configuration information for the
// flow types supported.
Flows *OAuthFlows
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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
// Description of the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
Description string
// 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
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 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
// Default value to use for substitution, which SHALL be sent if an alternate value is not supplied.
Default string
// Description for the server variable. CommonMark syntax MAY be used for rich text representation.
Description string
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
ServerVariable for server URL template substitution.
func (*ServerVariable) MarshalJSON ¶
func (v *ServerVariable) MarshalJSON() ([]byte, error)
type StatusError ¶
StatusError is an error that has an HTTP status code. When returned from an operation handler, this sets the response status code before sending it to the client.
func Error400BadRequest ¶
func Error400BadRequest(msg string, errs ...error) StatusError
Error400BadRequest returns a 400.
func Error401Unauthorized ¶
func Error401Unauthorized(msg string, errs ...error) StatusError
Error401Unauthorized returns a 401.
func Error403Forbidden ¶
func Error403Forbidden(msg string, errs ...error) StatusError
Error403Forbidden returns a 403.
func Error404NotFound ¶
func Error404NotFound(msg string, errs ...error) StatusError
Error404NotFound returns a 404.
func Error405MethodNotAllowed ¶
func Error405MethodNotAllowed(msg string, errs ...error) StatusError
Error405MethodNotAllowed returns a 405.
func Error406NotAcceptable ¶
func Error406NotAcceptable(msg string, errs ...error) StatusError
Error406NotAcceptable returns a 406.
func Error409Conflict ¶
func Error409Conflict(msg string, errs ...error) StatusError
Error409Conflict returns a 409.
func Error410Gone ¶
func Error410Gone(msg string, errs ...error) StatusError
Error410Gone returns a 410.
func Error412PreconditionFailed ¶
func Error412PreconditionFailed(msg string, errs ...error) StatusError
Error412PreconditionFailed returns a 412.
func Error415UnsupportedMediaType ¶
func Error415UnsupportedMediaType(msg string, errs ...error) StatusError
Error415UnsupportedMediaType returns a 415.
func Error422UnprocessableEntity ¶
func Error422UnprocessableEntity(msg string, errs ...error) StatusError
Error422UnprocessableEntity returns a 422.
func Error429TooManyRequests ¶
func Error429TooManyRequests(msg string, errs ...error) StatusError
Error429TooManyRequests returns a 429.
func Error500InternalServerError ¶
func Error500InternalServerError(msg string, errs ...error) StatusError
Error500InternalServerError returns a 500.
func Error501NotImplemented ¶
func Error501NotImplemented(msg string, errs ...error) StatusError
Error501NotImplemented returns a 501.
func Error502BadGateway ¶
func Error502BadGateway(msg string, errs ...error) StatusError
Error502BadGateway returns a 502.
func Error503ServiceUnavailable ¶
func Error503ServiceUnavailable(msg string, errs ...error) StatusError
Error503ServiceUnavailable returns a 503.
func Error504GatewayTimeout ¶
func Error504GatewayTimeout(msg string, errs ...error) StatusError
Error504GatewayTimeout returns a 504.
func Status304NotModified ¶
func Status304NotModified() StatusError
Status304NotModified returns a 304. This is not really an error, but provides a way to send non-default responses.
type StatusProvider ¶
type StatusProvider interface {
Status() int
}
StatusProvider allows output structs to provide HTTP status code. If an output struct implements this interface, the Status() method will be called to determine the HTTP status code for the response.
type Tag ¶
type Tag struct {
// Name is REQUIRED. The name of the tag.
Name string
// Description for the tag. CommonMark syntax MAY be used for rich text
// representation.
Description string
// ExternalDocs is additional external documentation for this tag.
ExternalDocs *ExternalDocs
// Extensions (user-defined properties), if any. Values in this map will
// be marshalled as siblings of the other properties above.
Extensions map[string]any
}
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 Transformer ¶
Transformer is a function that transforms response bodies before serialization. Transformers are run in the order they are added. Parameters:
- r: The HTTP request (for context-aware transformations)
- status: The HTTP status code as an integer (e.g., 200, 404)
- result: The response body value to transform (must be a struct from the output struct's Body field)
Returns the transformed value (which may be the same or a different type) and an error. Each transformer receives the output of the previous transformer in the chain. Note: Transformers are only called for struct body types. []byte and function bodies bypass transformers and are handled separately.
type Validator ¶
type Validator interface {
// Validate validates the input struct.
// Returns nil if validation succeeds, or a slice of errors if validation fails.
Validate(ctx context.Context, input any, metadata *schema.StructMetadata) []error
}
Validator validates input structs after request decoding. Each returned error should implement ErrorDetailer for RFC 9457 compliant responses.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package conditional provides utilities for HTTP conditional requests using If-Match, If-None-Match, If-Modified-Since, and If-Unmodified-Since headers.
|
Package conditional provides utilities for HTTP conditional requests using If-Match, If-None-Match, If-Modified-Since, and If-Unmodified-Since headers. |
|
examples
|
|
|
auth-jwt
command
auth-jwt demonstrates declarative role-based security using Zorya's Secure() helper.
|
auth-jwt demonstrates declarative role-based security using Zorya's Secure() helper. |
|
basic-crud
command
basic-crud demonstrates a complete CRUD API for a User resource using the Chi adapter.
|
basic-crud demonstrates a complete CRUD API for a User resource using the Chi adapter. |
|
conditional-requests
command
conditional-requests demonstrates HTTP conditional request support using conditional.Params.
|
conditional-requests demonstrates HTTP conditional request support using conditional.Params. |
|
content-negotiation
command
content-negotiation demonstrates automatic JSON/CBOR format selection based on the Accept header.
|
content-negotiation demonstrates automatic JSON/CBOR format selection based on the Accept header. |
|
fiber-adapter
command
fiber-adapter re-implements the basic CRUD example using the Fiber adapter.
|
fiber-adapter re-implements the basic CRUD example using the Fiber adapter. |
|
file-upload
command
file-upload demonstrates multipart file uploads using *multipart.FileHeader.
|
file-upload demonstrates multipart file uploads using *multipart.FileHeader. |
|
openapi-ui
command
openapi-ui demonstrates full OpenAPI 3.1 configuration with Bearer auth, multiple servers, operation metadata, and the Stoplight Elements docs UI.
|
openapi-ui demonstrates full OpenAPI 3.1 configuration with Bearer auth, multiple servers, operation metadata, and the Stoplight Elements docs UI. |
|
route-groups
command
route-groups demonstrates versioned API routing with NewGroup.
|
route-groups demonstrates versioned API routing with NewGroup. |
|
streaming-sse
command
streaming-sse demonstrates Server-Sent Events (SSE) using Zorya's streaming body pattern.
|
streaming-sse demonstrates Server-Sent Events (SSE) using Zorya's streaming body pattern. |
|
validation
command
validation demonstrates a custom Validator wrapping go-playground/validator.
|
validation demonstrates a custom Validator wrapping go-playground/validator. |