huma

package module
v0.0.0-...-f755f48 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2022 License: MIT Imports: 19 Imported by: 1

README

This fork has been shut down, please use https://huma.rocks/ instead!

Files have been left intact so existing imports continue to work, however no new commits will be made to this repository. You have been warned!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetConn

func GetConn(ctx context.Context) net.Conn

GetConn gets the underlying `net.Conn` from a context.

func RapiDocHandler

func RapiDocHandler(router *Router) http.Handler

RapiDocHandler renders documentation using RapiDoc.

func ReDocHandler

func ReDocHandler(router *Router) http.Handler

ReDocHandler renders documentation using ReDoc.

func SwaggerUIHandler

func SwaggerUIHandler(router *Router) http.Handler

SwaggerUIHandler renders documentation using Swagger UI.

Types

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{})
}

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 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

func (o *Operation) BodyReadTimeout(duration time.Duration)

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) MaxBodyBytes

func (o *Operation) MaxBodyBytes(size int64)

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

func (o *Operation) RequestSchema(s *schema.Schema)

RequestSchema allows overriding the generated input body schema, giving you more control over documentation and validation.

func (*Operation) Run

func (o *Operation) Run(handler interface{})

Run registers the handler function for this operation. It should be of the form: `func (ctx huma.Context)` or `func (ctx huma.Context, input)` where input is your input struct describing the input parameters and/or body.

type OperationInfo

type OperationInfo struct {
	ID          string
	URITemplate string
	Summary     string
	Tags        []string
}

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

type Resolver interface {
	Resolve(ctx Context, r *http.Request)
}

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) Delete

func (r *Resource) Delete(operationID, docs string, responses ...Response) *Operation

Delete creates a new HTTP DELETE operation at this resource.

func (*Resource) Get

func (r *Resource) Get(operationID, docs string, responses ...Response) *Operation

Get creates a new HTTP GET operation at this resource.

func (*Resource) Head

func (r *Resource) Head(operationID, docs string, responses ...Response) *Operation

Head creates a new HTTP HEAD operation at this resource.

func (*Resource) Middleware

func (r *Resource) Middleware(middlewares ...func(next http.Handler) http.Handler)

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

func (r *Resource) Operation(method, operationID, docs string, responses ...Response) *Operation

Operation creates a new HTTP operation with the given method at this resource.

func (*Resource) Patch

func (r *Resource) Patch(operationID, docs string, responses ...Response) *Operation

Patch creates a new HTTP PATCH operation at this resource.

func (*Resource) Post

func (r *Resource) Post(operationID, docs string, responses ...Response) *Operation

Post creates a new HTTP POST operation at this resource.

func (*Resource) Put

func (r *Resource) Put(operationID, docs string, responses ...Response) *Operation

Put creates a new HTTP PUT operation at this resource.

func (*Resource) SubResource

func (r *Resource) SubResource(path string) *Resource

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.

func (*Resource) Tags

func (r *Resource) Tags(names ...string)

Tags appends to the list of tags, used for documentation.

type Response

type Response struct {
	// contains filtered or unexported fields
}

Response describes an HTTP response that can be returned from an operation.

func NewResponse

func NewResponse(status int, description string) Response

NewResponse creates a new response representation.

func (Response) ContentType

func (r Response) ContentType(ct string) Response

ContentType sets the response's content type header.

func (Response) GetStatus

func (r Response) GetStatus() int

GetStatus returns the response's HTTP status code.

func (Response) Headers

func (r Response) Headers(names ...string) Response

Headers returns a new response with the named headers added. Sending headers to the client is optional, but they must be named here before you can send them.

func (Response) Model

func (r Response) Model(bodyModel interface{}) Response

Model returns a new response with the given model representing the body. Because Go cannot pass types, `bodyModel` should be an instance of the response body.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router is the entrypoint to your API.

func New

func New(docs, version string) *Router

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) Contact

func (r *Router) Contact(name, email, url string)

Contact sets the API's contact information.

func (*Router) DefaultBodyReadTimeout

func (r *Router) DefaultBodyReadTimeout(timeout time.Duration)

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

func (r *Router) DefaultServerIdleTimeout(timeout time.Duration)

DefaultServerIdleTimeout sets the server's `IdleTimeout` value on startup. Defaults to 15 seconds if not set.

func (*Router) DocsHandler

func (r *Router) DocsHandler(handler http.Handler)

DocsHandler sets the http.Handler to render documentation. It defaults to using RapiDoc.

func (*Router) DocsPrefix

func (r *Router) DocsPrefix(path string)

DocsPrefix sets the path prefix for where the OpenAPI JSON and documentation are hosted.

func (*Router) GatewayAuthCode

func (r *Router) GatewayAuthCode(name, authorizeURL, tokenURL string, scopes map[string]string)

GatewayAuthCode documents that the API gateway handles auth using OAuth2 authorization code (user login).

func (*Router) GatewayBasicAuth

func (r *Router) GatewayBasicAuth(name string)

GatewayBasicAuth documents that the API gateway handles auth using HTTP Basic.

func (*Router) GatewayClientCredentials

func (r *Router) GatewayClientCredentials(name, tokenURL string, scopes map[string]string)

GatewayClientCredentials documents that the API gateway handles auth using OAuth2 client credentials (pre-shared secret).

func (*Router) GetTitle

func (r *Router) GetTitle() string

GetTitle returns the server API title.

func (*Router) GetVersion

func (r *Router) GetVersion() string

GetVersion returns the server version.

func (*Router) Listen

func (r *Router) Listen(addr string) error

Listen starts the server listening on the specified `host:port` address.

func (*Router) ListenTLS

func (r *Router) ListenTLS(addr, certFile, keyFile string) error

ListenTLS listens for new connections using HTTPS & HTTP2

func (*Router) Middleware

func (r *Router) Middleware(middlewares ...func(next http.Handler) http.Handler)

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

func (r *Router) OpenAPIPath() string

OpenAPIPath returns the server path to the OpenAPI JSON.

func (*Router) Resource

func (r *Router) Resource(path string) *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) SecurityRequirement

func (r *Router) SecurityRequirement(name string, scopes ...string)

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 (r *Router) ServerLink(description, uri string)

ServerLink adds a new server link to this router for documentation.

func (*Router) Shutdown

func (r *Router) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server.

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.

Jump to

Keyboard shortcuts

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