Documentation
¶
Index ¶
- Constants
- func AddAllowedHeaders(name ...string)
- func GetConn(ctx context.Context) net.Conn
- func RapiDocHandler(router *Router) http.Handler
- func ReDocHandler(router *Router) http.Handler
- func StoplightElementsHandler(router *Router) http.Handler
- func SwaggerUIHandler(router *Router) http.Handler
- type APIKeyLocation
- type AutoConfig
- type AutoConfigVar
- type Context
- type ErrorDetail
- type ErrorDetailer
- type ErrorModel
- type GraphQLConfig
- type GraphQLDefaultPaginator
- type GraphQLHeaders
- type GraphQLItems
- type GraphQLPaginationParams
- type GraphQLPaginator
- type Operation
- func (o *Operation) BodyReadTimeout(duration time.Duration)
- func (o *Operation) Deprecated()
- func (o *Operation) MaxBodyBytes(size int64)
- func (o *Operation) NoBodyReadTimeout()
- func (o *Operation) NoMaxBody()
- func (o *Operation) RequestSchema(s *schema.Schema)
- func (o *Operation) RequestSchemaForContentType(ct string, s *schema.Schema)
- func (o *Operation) Run(handler interface{})
- type OperationInfo
- type Resolver
- type Resource
- func (r *Resource) Delete(operationID, docs string, responses ...Response) *Operation
- func (r *Resource) Get(operationID, docs string, responses ...Response) *Operation
- func (r *Resource) Head(operationID, docs string, responses ...Response) *Operation
- func (r *Resource) Hidden()
- func (r *Resource) Middleware(middlewares ...func(next http.Handler) http.Handler)
- func (r *Resource) Operation(method, operationID, docs string, responses ...Response) *Operation
- func (r *Resource) Patch(operationID, docs string, responses ...Response) *Operation
- func (r *Resource) Post(operationID, docs string, responses ...Response) *Operation
- func (r *Resource) Put(operationID, docs string, responses ...Response) *Operation
- func (r *Resource) SubResource(path string) *Resource
- func (r *Resource) Tags(names ...string)
- type Response
- type Router
- func (r *Router) AutoConfig(autoConfig AutoConfig)
- func (r *Router) AutoPatch()
- func (r *Router) Contact(name, email, url string)
- func (r *Router) DefaultBodyReadTimeout(timeout time.Duration)
- func (r *Router) DefaultServerIdleTimeout(timeout time.Duration)
- func (r *Router) DisableAutoPatch()
- func (r *Router) DisableSchemaProperty()
- func (r *Router) DocsHandler(handler http.Handler)
- func (r *Router) DocsPath() string
- func (r *Router) DocsPrefix(path string)
- func (r *Router) DocsSuffix(suffix string)
- func (r *Router) EnableGraphQL(config *GraphQLConfig)
- func (r *Router) GatewayAPIKey(name string, description string, keyName string, in APIKeyLocation)
- func (r *Router) GatewayAuthCode(name, authorizeURL, tokenURL string, scopes map[string]string)
- func (r *Router) GatewayBasicAuth(name string)
- func (r *Router) GatewayBearerFormat(name string, description string, format string)
- func (r *Router) GatewayClientCredentials(name, tokenURL string, scopes map[string]string)
- func (r *Router) GatewayOpenIDConnect(name string, description string, url string)
- func (r *Router) GetOperation(id string) *OperationInfo
- func (r *Router) GetTitle() string
- func (r *Router) GetVersion() string
- func (r *Router) Listen(addr string) error
- func (r *Router) ListenTLS(addr, certFile, keyFile string) error
- func (r *Router) Middleware(middlewares ...func(next http.Handler) http.Handler)
- func (r *Router) OpenAPI() *gabs.Container
- func (r *Router) OpenAPIHook(hook func(*gabs.Container))
- func (r *Router) OpenAPIPath() string
- func (r *Router) Resource(path string) *Resource
- func (r *Router) SchemasPath() string
- func (r *Router) SchemasSuffix(suffix string)
- func (r *Router) SecurityRequirement(name string, scopes ...string)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) ServerLink(description, uri string)
- func (r *Router) Shutdown(ctx context.Context) error
- func (r *Router) SpecSuffix(suffix string)
- func (r *Router) URLPrefix(value string)
- type SecurityScheme
Constants ¶
const ( DefaultDocsSuffix = "docs" DefaultSchemasSuffix = "schemas" DefaultSpecSuffix = "openapi" )
Variables ¶
This section is empty.
Functions ¶
func AddAllowedHeaders ¶ added in v1.11.0
func AddAllowedHeaders(name ...string)
AddAllowedHeader adds a header to the list of allowed headers for the response. This is useful for common headers that might be sent due to middleware or other frameworks
func RapiDocHandler ¶
RapiDocHandler renders documentation using RapiDoc.
func ReDocHandler ¶
ReDocHandler renders documentation using ReDoc.
func StoplightElementsHandler ¶ added in v1.14.0
StoplightElementsHandler renders documentation using Stoplight Elements.
func SwaggerUIHandler ¶
SwaggerUIHandler renders documentation using Swagger UI.
Types ¶
type APIKeyLocation ¶ added in v1.11.0
type APIKeyLocation string
paramLocation describes where in the HTTP request the parameter comes from.
type AutoConfig ¶
type AutoConfig struct { Security string `json:"security"` Headers map[string]string `json:"headers,omitempty"` Prompt map[string]AutoConfigVar `json:"prompt,omitempty"` Params map[string]string `json:"params"` }
AutoConfig holds an API's automatic configuration settings for the CLI. These are advertised via OpenAPI extension and picked up by the CLI to make it easier to get started using an API.
type AutoConfigVar ¶
type AutoConfigVar struct { Description string `json:"description,omitempty"` Example string `json:"example,omitempty"` Default interface{} `json:"default,omitempty"` Enum []interface{} `json:"enum,omitempty"` // Exclude the value from being sent to the server. This essentially makes // it a value which is only used in param templates. Exclude bool `json:"exclude,omitempty"` }
AutoConfigVar represents a variable given by the user when prompted during auto-configuration setup of an API.
type Context ¶
type Context interface { context.Context http.ResponseWriter // WithValue returns a shallow copy of the context with a new context value // applied to it. WithValue(key, value interface{}) Context // SetValue sets a context value. The Huma context is modified in place while // the underlying request context is copied. This is particularly useful for // setting context values from input resolver functions. SetValue(key, value interface{}) // AddError adds a new error to the list of errors for this request. AddError(err error) // HasError returns true if at least one error has been added to the context. HasError() bool // WriteError writes out an HTTP status code, friendly error message, and // optionally a set of error details set with `AddError` and/or passed in. WriteError(status int, message string, errors ...error) // WriteModel writes out an HTTP status code and marshalled model based on // content negotiation (e.g. JSON or CBOR). This must match the registered // response status code & type. WriteModel(status int, model interface{}) // WriteContent wraps http.ServeContent in order to handle serving streams // it will handle Range and Modified (like If-Unmodified-Since) headers. WriteContent(name string, content io.ReadSeeker, lastModified time.Time) // Implement the http.Flusher interface Flush() }
Context provides a request context and response writer with convenience functions for error and model marshaling in handler functions.
func ContextFromRequest ¶
func ContextFromRequest(w http.ResponseWriter, r *http.Request) Context
ContextFromRequest returns a Huma context for a request, useful for accessing high-level convenience functions from e.g. middleware.
type ErrorDetail ¶
type ErrorDetail struct { Message string `json:"message,omitempty" doc:"Error message text"` Location string `json:"location,omitempty" doc:"Where the error occured, e.g. 'body.items[3].tags' or 'path.thing-id'"` Value interface{} `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.
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.
type ErrorModel ¶
type ErrorModel struct { // Type is a URI to get more information about the error type. Type string `` /* 170-byte string literal not displayed */ // Title provides a short static summary of the problem. Huma will default this // to the HTTP response status code text if not present. Title string `` /* 165-byte string literal not displayed */ // Status provides the HTTP status code for client convenience. Huma 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" example:"400" doc:"HTTP status code"` // Detail is an explanation specific to this error occurrence. Detail string `` /* 153-byte string literal not displayed */ // Instance is a URI to get more info about this error occurence. Instance string `` /* 162-byte string literal not displayed */ // Errors provides an optional mechanism of passing additional error details // as a list. Errors []*ErrorDetail `json:"errors,omitempty" doc:"Optional list of individual error details"` }
ErrorModel defines a basic error message model.
type GraphQLConfig ¶ added in v1.1.0
type GraphQLConfig struct { // Path where the GraphQL endpoint is available. Defaults to `/graphql`. Path string // GraphiQL sets whether the UI is available at the path. Defaults to off. GraphiQL bool // ComplexityLimit sets the maximum allowed complexity, which is calculated // as 1 for each field and 2 + (n * child) for each array with n children // created from sub-resource requests. ComplexityLimit int // Paginator defines the struct to be used for paginated responses. This // can be used to conform to different pagination styles if the underlying // API supports them, such as Relay. If not set, then // `GraphQLDefaultPaginator` is used. Paginator GraphQLPaginator // IgnorePrefixes defines path prefixes which should be ignored by the // GraphQL model generator. IgnorePrefixes []string // contains filtered or unexported fields }
type GraphQLDefaultPaginator ¶ added in v1.1.0
type GraphQLDefaultPaginator struct { Headers GraphQLHeaders `json:"headers"` Links GraphQLPaginationParams `json:"links" doc:"Pagination link parameters"` Edges GraphQLItems `json:"edges"` }
GraphQLDefaultPaginator provides a default generic paginator implementation that makes no assumptions about pagination parameter names, headers, etc. It enables clients to access the response items (edges) as well as any response headers. If a link relation header is found in the response, then link relationships are parsed and turned into easy-to-use parameters for subsequent requests.
type GraphQLHeaders ¶ added in v1.1.0
GraphQLHeaders is a placeholder to be used in `GraphQLPaginator` struct implementations which gets replaced with a struct of response headers.
type GraphQLItems ¶ added in v1.1.0
type GraphQLItems []interface{}
GraphQLItems is a placeholder to be used in `GraphQLPaginator` struct implementations which gets replaced with a list of the response items model.
type GraphQLPaginationParams ¶ added in v1.1.0
type GraphQLPaginationParams struct { First map[string]string `json:"first" doc:"First page link relationship"` Next map[string]string `json:"next" doc:"Next page link relationship"` Prev map[string]string `json:"prev" doc:"Previous page link relationship"` Last map[string]string `json:"last" doc:"Last page link relationship"` }
GraphQLPaginationParams provides params for link relationships so that new GraphQL queries to get e.g. the next page of items are easy to construct.
type GraphQLPaginator ¶ added in v1.1.0
type GraphQLPaginator interface { // Load the paginated response from the given headers and body. After this // call completes, your struct instance should be ready to send back to // the client. Load(headers map[string]string, body []interface{}) error }
GraphQLPaginator defines how to to turn list responses from the HTTP API to GraphQL response objects.
type Operation ¶
type Operation struct {
// contains filtered or unexported fields
}
Operation represents an operation (an HTTP verb, e.g. GET / PUT) against a resource attached to a router.
func (*Operation) BodyReadTimeout ¶
BodyReadTimeout sets the amount of time a request can spend reading the body, after which it times out and the request is cancelled. The default is 15 seconds.
func (*Operation) Deprecated ¶ added in v1.12.0
func (o *Operation) Deprecated()
Deprecated marks the operation is deprecated, warning consumers should refrain from using this.
func (*Operation) MaxBodyBytes ¶
MaxBodyBytes sets the max number of bytes that the request body size may be before the request is cancelled. The default is 1MiB.
func (*Operation) NoBodyReadTimeout ¶
func (o *Operation) NoBodyReadTimeout()
NoBodyReadTimeout removes the body read timeout, which is 15 seconds by default. Use this if you expect to stream the input request or need to handle very large request bodies.
func (*Operation) NoMaxBody ¶
func (o *Operation) NoMaxBody()
NoMaxBody removes the body byte limit, which is 1MiB by default. Use this if you expect to stream the input request or need to handle very large request bodies.
func (*Operation) RequestSchema ¶
RequestSchema allows overriding the generated input body schema, giving you more control over documentation and validation.
func (*Operation) RequestSchemaForContentType ¶ added in v1.11.0
type OperationInfo ¶
OperationInfo describes an operation. It contains useful information for logging, metrics, auditing, etc.
func GetOperationInfo ¶
func GetOperationInfo(ctx context.Context) *OperationInfo
GetOperationInfo returns information about the current Huma operation. This will only be populated *after* routing has been handled, meaning *after* `next.ServeHTTP(w, r)` has been called in your middleware.
type Resolver ¶
Resolver provides a way to resolve input values from a request or to post- process input values in some way, including additional validation beyond what is possible with JSON Schema alone. If any errors are added to the context, then the client will get a 400 Bad Request response.
type Resource ¶
type Resource struct {
// contains filtered or unexported fields
}
Resource represents an API resource attached to a router at a specific path (URI template). Resources can have operations or subresources attached to them.
func (*Resource) Hidden ¶ added in v1.6.0
func (r *Resource) Hidden()
Hidden removes this resource from the OpenAPI spec and documentation. It is intended to be used for things like health check endpoints.
func (*Resource) Middleware ¶
Middleware adds a new standard middleware to this resource, so it will apply to requests at the resource's path (including any subresources). Middleware can also be applied at the router level to apply to all requests.
func (*Resource) Operation ¶
Operation creates a new HTTP operation with the given method at this resource.
func (*Resource) SubResource ¶
SubResource creates a new resource attached to this resource. The passed path will be appended to the resource's existing path. The path can include parameters, e.g. `/things/{thing-id}`. Each resource path must be unique.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response describes an HTTP response that can be returned from an operation.
func NewResponse ¶
NewResponse creates a new response representation.
func (Response) ContentType ¶
ContentType sets the response's content type header.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is the entrypoint to your API.
func New ¶
New creates a new Huma router to which you can attach resources, operations, middleware, etc.
func (*Router) AutoConfig ¶
func (r *Router) AutoConfig(autoConfig AutoConfig)
AutoConfig sets up CLI autoconfiguration via `x-cli-config` for use by CLI clients, e.g. using a tool like Restish (https://rest.sh/).
func (*Router) AutoPatch ¶ added in v1.11.0
func (r *Router) AutoPatch()
AutoPatch generates HTTP PATCH operations for any resource which has a GET & PUT but no pre-existing PATCH operation. Generated PATCH operations will call GET, apply either `application/merge-patch+json` or `application/json-patch+json` patches, then call PUT with the updated resource. This method is called automatically on server start-up but can be called manually (e.g. for tests) and is idempotent.
func (*Router) DefaultBodyReadTimeout ¶
DefaultBodyReadTimeout sets the amount of time an operation has to read the body of the incoming request before it is aborted. Defaults to 15 seconds if not set.
func (*Router) DefaultServerIdleTimeout ¶
DefaultServerIdleTimeout sets the server's `IdleTimeout` value on startup. Defaults to 15 seconds if not set.
func (*Router) DisableAutoPatch ¶ added in v1.11.0
func (r *Router) DisableAutoPatch()
DisableAutoPatch disables the automatic generation of HTTP PATCH operations whenever a GET/PUT combo exists without a pre-existing PATCH.
func (*Router) DisableSchemaProperty ¶ added in v1.3.0
func (r *Router) DisableSchemaProperty()
DisableSchemaProperty disables the creation of a `$schema` property in returned object response models.
func (*Router) DocsHandler ¶
DocsHandler sets the http.Handler to render documentation. It defaults to using RapiDoc.
func (*Router) DocsPrefix ¶
DocsPrefix sets the path prefix for where the OpenAPI JSON, schemas, and documentation are hosted.
func (*Router) DocsSuffix ¶ added in v1.8.0
DocsSuffix sets the final path suffix for where the OpenAPI documentation is hosted. When not specified, the default value of `docs` is appended to the DocsPrefix.
func (*Router) EnableGraphQL ¶ added in v1.1.0
func (r *Router) EnableGraphQL(config *GraphQLConfig)
EnableGraphQL turns on a read-only GraphQL endpoint.
func (*Router) GatewayAPIKey ¶ added in v1.11.0
func (r *Router) GatewayAPIKey(name string, description string, keyName string, in APIKeyLocation)
GatewayAPIKey documents that the API gateway handles auth using API Key.
func (*Router) GatewayAuthCode ¶
GatewayAuthCode documents that the API gateway handles auth using OAuth2 authorization code (user login).
func (*Router) GatewayBasicAuth ¶
GatewayBasicAuth documents that the API gateway handles auth using HTTP Basic.
func (*Router) GatewayBearerFormat ¶ added in v1.11.0
GatewayBearerFormat documents that the API gateway handles auth using HTTP Bearer.
func (*Router) GatewayClientCredentials ¶
GatewayClientCredentials documents that the API gateway handles auth using OAuth2 client credentials (pre-shared secret).
func (*Router) GatewayOpenIDConnect ¶ added in v1.11.0
GatewayOpenIDConnect documents that the API gateway handles auth using openIdConnect.
func (*Router) GetOperation ¶ added in v1.13.0
func (r *Router) GetOperation(id string) *OperationInfo
GetOperation returns an `OperationInfo` struct for the operation named by the `id` argument. The `OperationInfo` struct provides the URL template and a summary of the operation along with any tags associated with the operation.
func (*Router) GetVersion ¶
GetVersion returns the server version.
func (*Router) Middleware ¶
Middleware adds a new standard middleware to this router at the root, so it will apply to all requests. Middleware can also be applied at the resource level.
func (*Router) OpenAPI ¶
func (r *Router) OpenAPI() *gabs.Container
OpenAPI returns an OpenAPI 3 representation of the API, which can be modified as needed and rendered to JSON via `.String()`.
func (*Router) OpenAPIHook ¶
func (r *Router) OpenAPIHook(hook func(*gabs.Container))
OpenAPIHook provides a function to run after generating the OpenAPI document allowing you to modify it as needed.
func (*Router) OpenAPIPath ¶
OpenAPIPath returns the server path to the OpenAPI JSON.
func (*Router) Resource ¶
Resource creates a new resource attached to this router at the given path. The path can include parameters, e.g. `/things/{thing-id}`. Each resource path must be unique.
func (*Router) SchemasPath ¶ added in v1.8.0
SchemasPath returns the server path to the OpenAPI Schemas.
func (*Router) SchemasSuffix ¶ added in v1.8.0
SchemasSuffix sets the final path suffix for where the OpenAPI schemas are hosted. When not specified, the default value of `schemas` is appended to the DocsPrefix.
func (*Router) SecurityRequirement ¶
SecurityRequirement sets up a security requirement for the entire API by name and with the given scopes. Use together with the other auth options like GatewayAuthCode. Calling multiple times results in requiring one OR the other schemes but not both.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP handles an incoming request and is compatible with the standard library `http` package.
func (*Router) ServerLink ¶
ServerLink adds a new server link to this router for documentation.
func (*Router) SpecSuffix ¶ added in v1.8.0
SpecSuffix sets the final path suffix for where the OpenAPI spec is hosted. When not specified, the default value of `openapi` is appended to the DocsPrefix.
func (*Router) URLPrefix ¶ added in v1.3.0
URLPrefix sets the prefix to use when crafting non-relative links. If unset, then the incoming requests `Host` header is used and the scheme defaults to `https` unless the host starts with `localhost`. Do not include a trailing slash in the prefix. Examples: - https://example.com/v1 - http://localhost
type SecurityScheme ¶ added in v1.11.0
type SecurityScheme string
const ( SecuritySchemeApiKey SecurityScheme = "apiKey" SecuritySchemeHTTP SecurityScheme = "http" SecuritySchemeOauth2 SecurityScheme = "oauth2" SecuritySchemeOpenIdConnect SecurityScheme = "openIdConnect" )
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
benchmark
module
|
|
examples
|
|
Package humatest provides testing utilities for testing Huma-powered services.
|
Package humatest provides testing utilities for testing Huma-powered services. |
Package schema implements OpenAPI 3 compatible JSON Schema which can be generated from structs.
|
Package schema implements OpenAPI 3 compatible JSON Schema which can be generated from structs. |