huma

package module
v2.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2024 License: MIT Imports: 32 Imported by: 160

README

Huma Logo

HUMA Powered CI codecov Docs Go Report Card

🌎中文文档

A modern, simple, fast & flexible micro framework for building HTTP REST/RPC APIs in Go backed by OpenAPI 3 and JSON Schema. Pronounced IPA: /'hjuːmɑ/. The goals of this project are to provide:

  • Incremental adoption for teams with existing services
    • Bring your own router (including Go 1.22+), middleware, and logging/metrics
    • Extensible OpenAPI & JSON Schema layer to document existing routes
  • A modern REST or HTTP RPC API backend framework for Go developers
  • Guard rails to prevent common mistakes
  • Documentation that can't get out of date
  • High-quality generated developer tooling

Features include:

  • Declarative interface on top of your router of choice:
    • Operation & model documentation
    • Request params (path, query, header, or cookie)
    • Request body
    • Responses (including errors)
    • Response headers
  • JSON Errors using RFC9457 and application/problem+json by default (but can be changed)
  • Per-operation request size limits with sane defaults
  • Content negotiation between server and client
    • Support for JSON (RFC 8259) and optionally CBOR (RFC 7049) content types via the Accept header with the default config.
  • Conditional requests support, e.g. If-Match or If-Unmodified-Since header utilities.
  • Optional automatic generation of PATCH operations that support:
  • Annotated Go types for input and output models
    • Generates JSON Schema from Go types
    • Static typing for path/query/header params, bodies, response headers, etc.
    • Automatic input model validation & error handling
  • Documentation generation using Stoplight Elements
  • Optional CLI built-in, configured via arguments or environment variables
    • Set via e.g. -p 8000, --port=8000, or SERVICE_PORT=8000
    • Startup actions & graceful shutdown built-in
  • Generates OpenAPI for access to a rich ecosystem of tools
  • Generates JSON Schema for each resource using optional describedby link relation headers as well as optional $schema properties in returned objects that integrate into editors for validation & completion.

This project was inspired by FastAPI. Logo & branding designed by Kari Taylor.

Sponsors

A big thank you to our current & former sponsors!

Zuplo

Zuplo: Scale, Protect, and Productize your Huma API

Our API Gateway allows you to secure your API, scale it globally, generate documentation from your OpenAPI, and monetize your users.

Start for Free

Testimonials

This is by far my favorite web framework for Go. It is inspired by FastAPI, which is also amazing, and conforms to many RFCs for common web things ... I really like the feature set, the fact that it [can use] Chi, and the fact that it is still somehow relatively simple to use. I've tried other frameworks and they do not spark joy for me. - Jeb_Jenky

After working with #Golang for over a year, I stumbled upon Huma, the #FastAPI-inspired web framework. It’s the Christmas miracle I’ve been hoping for! This framework has everything! - Hana Mohan

I love Huma. Thank you, sincerely, for this awesome package. I’ve been using it for some time now and it’s been great! - plscott

Thank you Daniel for Huma. Superbly useful project and saves us a lot of time and hassle thanks to the OpenAPI gen — similar to FastAPI in Python. - WolvesOfAllStreets

Huma is wonderful, I've started working with it recently, and it's a pleasure, so thank you very much for your efforts 🙏 - callmemicah

It took us 3 months to build our platform in Python with FastAPI, SQL Alchemy and only 3 weeks to rewrite it in Go with Huma and SQL C. Things just work and I seldomly have to debug where in Python I spent a majority of my time debugging. - Bitclick_

Look at Huma, it's great. A nice slim layer on top of stdlib mux/chi and automatic body and parameter serialization, kinda feels like doing dotnet web APIs, but forces you to actually design request and response structs, which is great imo. - Kirides

Install

Install via go get. Note that Go 1.21 or newer is required.

# After: go mod init ...
go get -u github.com/danielgtaylor/huma/v2

Example

Here is a complete basic hello world example in Huma, that shows how to initialize a Huma app complete with CLI, declare a resource operation, and define its handler function.

package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/danielgtaylor/huma/v2"
	"github.com/danielgtaylor/huma/v2/adapters/humachi"
	"github.com/danielgtaylor/huma/v2/humacli"
	"github.com/go-chi/chi/v5"

	_ "github.com/danielgtaylor/huma/v2/formats/cbor"
)

// Options for the CLI. Pass `--port` or set the `SERVICE_PORT` env var.
type Options struct {
	Port int `help:"Port to listen on" short:"p" default:"8888"`
}

// GreetingOutput represents the greeting operation response.
type GreetingOutput struct {
	Body struct {
		Message string `json:"message" example:"Hello, world!" doc:"Greeting message"`
	}
}

func main() {
	// Create a CLI app which takes a port option.
	cli := humacli.New(func(hooks humacli.Hooks, options *Options) {
		// Create a new router & API
		router := chi.NewMux()
		api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))

		// Add the operation handler to the API.
		huma.Get(api, "/greeting/{name}", func(ctx context.Context, input *struct{
			Name string `path:"name" maxLength:"30" example:"world" doc:"Name to greet"`
		}) (*GreetingOutput, error) {
			resp := &GreetingOutput{}
			resp.Body.Message = fmt.Sprintf("Hello, %s!", input.Name)
			return resp, nil
		})

		// Tell the CLI how to start your router.
		hooks.OnStart(func() {
			http.ListenAndServe(fmt.Sprintf(":%d", options.Port), router)
		})
	})

	// Run the CLI. When passed no commands, it starts the server.
	cli.Run()
}

[!TIP] Replace chi.NewMux()http.NewServeMux() and humachi.Newhumago.New to use the standard library router from Go 1.22+. Just make sure your go.mod has go 1.22 or newer listed in it. Everything else stays the same! Switch whenever you are ready.

You can test it with go run greet.go (optionally pass --port to change the default) and make a sample request using Restish (or curl):

# Get the message from the server
$ restish :8888/greeting/world
HTTP/1.1 200 OK
...
{
	$schema: "http://localhost:8888/schemas/GreetingOutputBody.json",
	message: "Hello, world!"
}

Even though the example is tiny you can also see some generated documentation at http://localhost:8888/docs. The generated OpenAPI is available at http://localhost:8888/openapi.json or http://localhost:8888/openapi.yaml.

Check out the Huma tutorial for a step-by-step guide to get started.

Documentation

See the https://huma.rocks/ website for full documentation in a presentation that's easier to navigate and search then this README. You can find the source for the site in the docs directory of this repo.

Official Go package documentation can always be found at https://pkg.go.dev/github.com/danielgtaylor/huma/v2.

Articles & Mentions

Be sure to star the project if you find it useful!

Star History Chart

Documentation

Overview

Package huma provides a framework for building REST APIs in Go. It is designed to be simple, fast, and easy to use. It is also designed to generate OpenAPI 3.1 specifications and JSON Schema documents describing the API and providing a quick & easy way to generate docs, mocks, SDKs, CLI clients, and more.

https://huma.rocks/

Index

Examples

Constants

View Source
const (
	TypeBoolean = "boolean"
	TypeInteger = "integer"
	TypeNumber  = "number"
	TypeString  = "string"
	TypeArray   = "array"
	TypeObject  = "object"
)

JSON Schema type constants

Variables

View Source
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.

View Source
var DefaultFormats = map[string]Format{
	"application/json": DefaultJSONFormat,
	"json":             DefaultJSONFormat,
}

DefaultFormats is a map of default formats that can be set in the API's `Config.Formats` map, used for content negotiation for marshaling and unmarshaling request/response bodies. This is used by the `DefaultConfig` function and can be modified to add or remove additional formats. For example, to add support for CBOR, simply import it:

import _ "github.com/danielgtaylor/huma/v2/formats/cbor"
View Source
var DefaultJSONFormat = Format{
	Marshal: func(w io.Writer, v any) error {
		return json.NewEncoder(w).Encode(v)
	},
	Unmarshal: json.Unmarshal,
}

DefaultJSONFormat is the default JSON formatter that can be set in the API's `Config.Formats` map. This is used by the `DefaultConfig` function.

config := huma.Config{}
config.Formats = map[string]huma.Format{
	"application/json": huma.DefaultJSONFormat,
	"json":             huma.DefaultJSONFormat,
}
View Source
var ErrSchemaInvalid = errors.New("schema is invalid")

ErrSchemaInvalid is sent when there is a problem building the schema.

View Source
var ErrUnknownContentType = errors.New("unknown content type")
View Source
var ErrorFormatter = fmt.Sprintf

ErrorFormatter is a function that formats an error message

View Source
var GenerateOperationID = func(method, path string, response any) string {
	action := method
	t := deref(reflect.TypeOf(response))
	if t.Kind() != reflect.Struct {
		panic("Response type must be a struct")
	}
	body, hasBody := t.FieldByName("Body")
	if hasBody && method == http.MethodGet && deref(body.Type).Kind() == reflect.Slice {

		action = "list"
	}
	return casing.Kebab(action + "-" + reRemoveIDs.ReplaceAllString(path, "by-$1"))
}

GenerateOperationID generates an operation ID from the method, path, and response type. The operation ID is used to uniquely identify an operation in the OpenAPI spec. The generated ID is kebab-cased and includes the method and path, with any path parameters replaced by their names.

Examples:

  • GET /things` -> `list-things
  • GET /things/{thing-id} -> get-things-by-thing-id
  • PUT /things/{thingId}/favorite -> put-things-by-thing-id-favorite

This function can be overridden to provide custom operation IDs.

View Source
var GenerateSummary = func(method, path string, response any) string {
	action := method
	t := deref(reflect.TypeOf(response))
	if t.Kind() != reflect.Struct {
		panic("Response type must be a struct")
	}
	body, hasBody := t.FieldByName("Body")
	if hasBody && method == http.MethodGet && deref(body.Type).Kind() == reflect.Slice {

		action = "list"
	}
	path = reRemoveIDs.ReplaceAllString(path, "by-$1")
	phrase := strings.ReplaceAll(casing.Kebab(strings.ToLower(action)+" "+path, strings.ToLower, casing.Initialism), "-", " ")
	return strings.ToUpper(phrase[:1]) + phrase[1:]
}

GenerateSummary generates an operation summary from the method, path, and response type. The summary is used to describe an operation in the OpenAPI spec. The generated summary is capitalized and includes the method and path, with any path parameters replaced by their names.

Examples:

  • GET /things` -> `List things`
  • GET /things/{thing-id} -> `Get things by thing id`
  • PUT /things/{thingId}/favorite -> `Put things by thing id favorite`

This function can be overridden to provide custom operation summaries.

View Source
var NewError = func(status int, msg string, errs ...error) StatusError {
	details := make([]*ErrorDetail, len(errs))
	for i := 0; i < len(errs); i++ {
		if converted, ok := errs[i].(ErrorDetailer); ok {
			details[i] = converted.ErrorDetail()
		} else {
			if errs[i] == nil {
				continue
			}
			details[i] = &ErrorDetail{Message: errs[i].Error()}
		}
	}
	return &ErrorModel{
		Status: status,
		Title:  http.StatusText(status),
		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. This function is used by all the error response utility functions, like `huma.Error400BadRequest`.

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
}

huma.NewError = func(status int, msg string, errs ...error) StatusError {
	return &MyError{
		status:  status,
		Message: msg,
		Errors:  errs,
	}
}
View Source
var NewErrorWithContext = func(_ Context, status int, msg string, errs ...error) StatusError {
	return NewError(status, msg, errs...)
}
View Source
var ValidateStrictCasing = false

ValidateStrictCasing controls whether or not field names are case-sensitive during validation. This is useful for clients that may send fields in a different case than expected by the server. For example, a legacy client may send `{"Foo": "bar"}` when the server expects `{"foo": "bar"}`. This is disabled by default to match Go's JSON unmarshaling behavior.

Functions

func AutoRegister

func AutoRegister(api API, server any)

AutoRegister auto-detects operation registration methods and registers them with the given API. Any method named `Register...` will be called and passed the API as the only argument. Since registration happens at service startup, no errors are returned and methods should panic on error.

type ItemsHandler struct {}

func (s *ItemsHandler) RegisterListItems(api API) {
	huma.Register(api, huma.Operation{
		OperationID: "ListItems",
		Method: http.MethodGet,
		Path: "/items",
	}, s.ListItems)
}

func main() {
	router := chi.NewMux()
	config := huma.DefaultConfig("My Service", "1.0.0")
	api := huma.NewExampleAPI(router, config)

	itemsHandler := &ItemsHandler{}
	huma.AutoRegister(api, itemsHandler)
}
Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/danielgtaylor/huma/v2"
	"github.com/go-chi/chi/v5"
)

// Item represents a single item with a unique ID.
type Item struct {
	ID string `json:"id"`
}

// ItemsResponse is a response containing a list of items.
type ItemsResponse struct {
	Body []Item `json:"body"`
}

// ItemsHandler handles item-related CRUD operations.
type ItemsHandler struct{}

// RegisterListItems registers the `list-items` operation with the given API.
// Because the method starts with `Register` it will be automatically called
// by `huma.AutoRegister` down below.
func (s *ItemsHandler) RegisterListItems(api huma.API) {
	// Register a list operation to get all the items.
	huma.Register(api, huma.Operation{
		OperationID: "list-items",
		Method:      http.MethodGet,
		Path:        "/items",
	}, func(ctx context.Context, input *struct{}) (*ItemsResponse, error) {
		resp := &ItemsResponse{}
		resp.Body = []Item{{ID: "123"}}
		return resp, nil
	})
}

func main() {
	// Create the router and API.
	router := chi.NewMux()
	api := NewExampleAPI(router, huma.DefaultConfig("My Service", "1.0.0"))

	// Create the item handler and register all of its operations.
	itemsHandler := &ItemsHandler{}
	huma.AutoRegister(api, itemsHandler)

	// Confirm the list operation was registered.
	fmt.Println(api.OpenAPI().Paths["/items"].Get.OperationID)
}
Output:

list-items

func DefaultSchemaNamer

func DefaultSchemaNamer(t reflect.Type, hint string) string

DefaultSchemaNamer provides schema names for types. It uses the type name when possible, ignoring the package name. If the type is generic, e.g. `MyType[SubType]`, then the brackets are removed like `MyTypeSubType`. If the type is unnamed, then the name hint is used. Note: if you plan to use types with the same name from different packages, you should implement your own namer function to prevent issues. Nested anonymous types can also present naming issues.

func Delete added in v2.7.0

func Delete[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), operationHandlers ...func(o *Operation))

Delete HTTP operation handler for an API. The handler must be a function that takes a context and a pointer to the input struct and returns a pointer to the output struct and an error. The input struct must be a struct with fields for the request path/query/header/cookie parameters and/or body. The output struct must be a struct with fields for the output headers and body of the operation, if any.

huma.Delete(api, "/things/{thing-id}", func(ctx context.Context, input *struct{
	ID string `path:"thing-id"`
}) (*struct{}, error) {
	// TODO: remove thing from DB...
	return nil, nil
})

This is a convenience wrapper around `huma.Register`.

func ErrorWithHeaders added in v2.14.0

func ErrorWithHeaders(err error, headers http.Header) error

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 Get added in v2.7.0

func Get[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), operationHandlers ...func(o *Operation))

Get HTTP operation handler for an API. The handler must be a function that takes a context and a pointer to the input struct and returns a pointer to the output struct and an error. The input struct must be a struct with fields for the request path/query/header/cookie parameters and/or body. The output struct must be a struct with fields for the output headers and body of the operation, if any.

huma.Get(api, "/things", func(ctx context.Context, input *struct{
	Body []Thing
}) (*ListThingOutput, error) {
	// TODO: list things from DB...
	resp := &PostThingOutput{}
	resp.Body = []Thing{{ID: "1", Name: "Thing 1"}}
	return resp, nil
})

This is a convenience wrapper around `huma.Register`.

func OperationTags added in v2.17.0

func OperationTags(tags ...string) func(o *Operation)

func Patch added in v2.7.0

func Patch[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), operationHandlers ...func(o *Operation))

Patch HTTP operation handler for an API. The handler must be a function that takes a context and a pointer to the input struct and returns a pointer to the output struct and an error. The input struct must be a struct with fields for the request path/query/header/cookie parameters and/or body. The output struct must be a struct with fields for the output headers and body of the operation, if any.

huma.Patch(api, "/things/{thing-id}", func(ctx context.Context, input *struct{
	ID string `path:"thing-id"`
	Body ThingPatch
}) (*PatchThingOutput, error) {
	// TODO: save thing to DB...
	resp := &PutThingOutput{}
	return resp, nil
})

This is a convenience wrapper around `huma.Register`.

func Post added in v2.7.0

func Post[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), operationHandlers ...func(o *Operation))

Post HTTP operation handler for an API. The handler must be a function that takes a context and a pointer to the input struct and returns a pointer to the output struct and an error. The input struct must be a struct with fields for the request path/query/header/cookie parameters and/or body. The output struct must be a struct with fields for the output headers and body of the operation, if any.

huma.Post(api, "/things", func(ctx context.Context, input *struct{
	Body Thing
}) (*PostThingOutput, error) {
	// TODO: save thing to DB...
	resp := &PostThingOutput{}
	resp.Location = "/things/" + input.Body.ID
	return resp, nil
})

This is a convenience wrapper around `huma.Register`.

func Put added in v2.7.0

func Put[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), operationHandlers ...func(o *Operation))

Put HTTP operation handler for an API. The handler must be a function that takes a context and a pointer to the input struct and returns a pointer to the output struct and an error. The input struct must be a struct with fields for the request path/query/header/cookie parameters and/or body. The output struct must be a struct with fields for the output headers and body of the operation, if any.

huma.Put(api, "/things/{thing-id}", func(ctx context.Context, input *struct{
	ID string `path:"thing-id"`
	Body Thing
}) (*PutThingOutput, error) {
	// TODO: save thing to DB...
	resp := &PutThingOutput{}
	return resp, nil
})

This is a convenience wrapper around `huma.Register`.

func ReadCookie added in v2.6.0

func ReadCookie(ctx Context, name string) (*http.Cookie, error)

ReadCookie reads a single cookie from the request headers by name. If multiple cookies with the same name exist, the first is returned.

func ReadCookies added in v2.6.0

func ReadCookies(ctx Context) []*http.Cookie

ReadCookies reads all cookies from the request headers.

func Register

func Register[I, O any](api API, op Operation, handler func(context.Context, *I) (*O, error))

Register an operation handler for an API. The handler must be a function that takes a context and a pointer to the input struct and returns a pointer to the output struct and an error. The input struct must be a struct with fields for the request path/query/header/cookie parameters and/or body. The output struct must be a struct with fields for the output headers and body of the operation, if any.

huma.Register(api, huma.Operation{
	OperationID: "get-greeting",
	Method:      http.MethodGet,
	Path:        "/greeting/{name}",
	Summary:     "Get a greeting",
}, func(ctx context.Context, input *GreetingInput) (*GreetingOutput, error) {
	if input.Name == "bob" {
		return nil, huma.Error404NotFound("no greeting for bob")
	}
	resp := &GreetingOutput{}
	resp.MyHeader = "MyValue"
	resp.Body.Message = fmt.Sprintf("Hello, %s!", input.Name)
	return resp, nil
})

func SetReadDeadline

func SetReadDeadline(w http.ResponseWriter, deadline time.Time) error

SetReadDeadline is a utility to set the read deadline on a response writer, if possible. If not, it will not incur any allocations (unlike the stdlib `http.ResponseController`). This is mostly a convenience function for adapters so they can be more efficient.

huma.SetReadDeadline(w, time.Now().Add(5*time.Second))

func Validate

func Validate(r Registry, s *Schema, path *PathBuffer, mode ValidateMode, v any, res *ValidateResult)

Validate an input value against a schema, collecting errors in the validation result object. If successful, `res.Errors` will be empty. It is suggested to use a `sync.Pool` to reuse the PathBuffer and ValidateResult objects, making sure to call `Reset()` on them before returning them to the pool.

registry := huma.NewMapRegistry("#/prefix", huma.DefaultSchemaNamer)
schema := huma.SchemaFromType(registry, reflect.TypeOf(MyType{}))
pb := huma.NewPathBuffer([]byte(""), 0)
res := &huma.ValidateResult{}

var value any
json.Unmarshal([]byte(`{"foo": "bar"}`), &v)
huma.Validate(registry, schema, pb, huma.ModeWriteToServer, value, res)
for _, err := range res.Errors {
	fmt.Println(err.Error())
}

func WriteErr

func WriteErr(api API, ctx Context, status int, msg string, errs ...error) error

WriteErr writes an error response with the given context, using the configured error type and with the given status code and message. It 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

	// OpenAPI returns the OpenAPI spec for this API. You may edit this spec
	// until the server starts.
	OpenAPI() *OpenAPI

	// Negotiate returns the selected content type given the client's `accept`
	// header and the server's supported content types. If the client does not
	// send an `accept` header, then JSON is used.
	Negotiate(accept string) (string, error)

	// Transform runs the API transformers on the given value. The `status` is
	// the key in the operation's `Responses` map that corresponds to the
	// response being sent (e.g. "200" for a 200 OK response).
	Transform(ctx Context, status string, v any) (any, error)

	// Marshal marshals the given value into the given writer. The
	// content type is used to determine which format to use. Use `Negotiate` to
	// get the content type from an accept header.
	Marshal(w io.Writer, contentType string, v any) error

	// Unmarshal unmarshals the given data into the given value. The content type
	Unmarshal(contentType string, data []byte, v any) error

	// UseMiddleware appends a middleware handler to the API middleware stack.
	//
	// The middleware stack for any API will execute before searching for a matching
	// route to a specific handler, which provides opportunity to respond early,
	// change the course of the request execution, or set request-scoped values for
	// the next Middleware.
	UseMiddleware(middlewares ...func(ctx Context, next func(Context)))

	// Middlewares returns a slice of middleware handler functions that will be
	// run for all operations. Middleware are run in the order they are added.
	// See also `huma.Operation{}.Middlewares` for adding operation-specific
	// middleware at operation registration time.
	Middlewares() Middlewares
}

API represents a Huma API wrapping a specific router.

func NewAPI

func NewAPI(config Config, a Adapter) API

NewAPI creates a new API with the given configuration and router adapter. You usually don't need to use this function directly, and can instead use the `New(...)` function provided by the adapter packages which call this function internally.

When the API is created, this function will ensure a schema registry exists (or create a new map registry if not), will set a default format if not set, and will set up the handlers for the OpenAPI spec, documentation, and JSON schema routes if the paths are set in the config.

router := chi.NewMux()
adapter := humachi.NewAdapter(router)
config := huma.DefaultConfig("Example API", "1.0.0")
api := huma.NewAPI(config, adapter)

type Adapter

type Adapter interface {
	Handle(op *Operation, handler func(ctx Context))
	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 `huma.Context` interface which abstracts away those router-specific differences.

The handler function takes uses the context to get request information like path / query / header params, the input body, and provide response data like a status code, response headers, and a response body.

Example (Handle)

ExampleAdapter_handle demonstrates how to use the adapter directly instead of using the `huma.Register` convenience function to add a new operation and handler to the API.

Note that you are responsible for defining all of the operation details, including the parameter and response definitions & schemas.

// Create an adapter for your chosen router.
adapter := NewExampleAdapter()

// Register an operation with a custom handler.
adapter.Handle(&huma.Operation{
	OperationID: "example-operation",
	Method:      "GET",
	Path:        "/example/{name}",
	Summary:     "Example operation",
	Parameters: []*huma.Param{
		{
			Name:        "name",
			In:          "path",
			Description: "Name to return",
			Required:    true,
			Schema: &huma.Schema{
				Type: "string",
			},
		},
	},
	Responses: map[string]*huma.Response{
		"200": {
			Description: "OK",
			Content: map[string]*huma.MediaType{
				"text/plain": {
					Schema: &huma.Schema{
						Type: "string",
					},
				},
			},
		},
	},
}, func(ctx huma.Context) {
	// Get the `name` path parameter.
	name := ctx.Param("name")

	// Set the response content type, status code, and body.
	ctx.SetHeader("Content-Type", "text/plain; charset=utf-8")
	ctx.SetStatus(http.StatusOK)
	ctx.BodyWriter().Write([]byte("Hello, " + name))
})
Output:

type AddOpFunc

type AddOpFunc func(oapi *OpenAPI, op *Operation)

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. This struct should be put into the `OpenAPI.Extensions` map under the key `x-cli-config`. See also: https://rest.sh/#/openapi?id=autoconfiguration

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 Components

type Components struct {
	// Schemas is an object to hold reusable Schema Objects.
	Schemas Registry `yaml:"schemas,omitempty"`

	// Responses is an object to hold reusable Response Objects.
	Responses map[string]*Response `yaml:"responses,omitempty"`

	// Parameters is an object to hold reusable Parameter Objects.
	Parameters map[string]*Param `yaml:"parameters,omitempty"`

	// Examples is an object to hold reusable Example Objects.
	Examples map[string]*Example `yaml:"examples,omitempty"`

	// RequestBodies is an object to hold reusable Request Body Objects.
	RequestBodies map[string]*RequestBody `yaml:"requestBodies,omitempty"`

	// Headers is an object to hold reusable Header Objects.
	Headers map[string]*Header `yaml:"headers,omitempty"`

	// SecuritySchemes is an object to hold reusable Security Scheme Objects.
	SecuritySchemes map[string]*SecurityScheme `yaml:"securitySchemes,omitempty"`

	// Links is an object to hold reusable Link Objects.
	Links map[string]*Link `yaml:"links,omitempty"`

	// Callbacks is an object to hold reusable Callback Objects.
	Callbacks map[string]*PathItem `yaml:"callbacks,omitempty"`

	// PathItems is an object to hold reusable Path Item Objects.
	PathItems map[string]*PathItem `yaml:"pathItems,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

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

components:
  schemas:
    GeneralError:
      type: object
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
    Category:
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
    Tag:
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
  parameters:
    skipParam:
      name: skip
      in: query
      description: number of items to skip
      required: true
      schema:
        type: integer
        format: int32
    limitParam:
      name: limit
      in: query
      description: max records to return
      required: true
      schema:
        type: integer
        format: int32
  responses:
    NotFound:
      description: Entity not found.
    IllegalInput:
      description: Illegal input for operation.
    GeneralError:
      description: General Error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GeneralError'
  securitySchemes:
    api_key:
      type: apiKey
      name: api_key
      in: header
    petstore_auth:
      type: oauth2
      flows:
        implicit:
          authorizationUrl: https://example.org/api/oauth/dialog
          scopes:
            write:pets: modify pets in your account
            read:pets: read your pets

func (*Components) MarshalJSON added in v2.4.0

func (c *Components) MarshalJSON() ([]byte, error)

type Config

type Config struct {
	// OpenAPI spec for the API. You should set at least the `Info.Title` and
	// `Info.Version` fields.
	*OpenAPI

	// OpenAPIPath is the path to the OpenAPI spec without extension. If set
	// to `/openapi` it will allow clients to get `/openapi.json` or
	// `/openapi.yaml`, for example.
	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

	// Formats defines the supported request/response formats by content type or
	// extension (e.g. `json` for `application/my-format+json`).
	Formats map[string]Format

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

	// Transformers are a way to modify a response body before it is serialized.
	Transformers []Transformer

	// CreateHooks is a list of functions that will be called before the API is
	// created. This allows you to modify the configuration at creation time,
	// for example if you need access to the path settings that may be changed
	// by the user after the defaults have been set.
	CreateHooks []func(Config) Config
}

Config represents a configuration for a new API. See `huma.DefaultConfig()` as a starting point.

func DefaultConfig

func DefaultConfig(title, version string) 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 registry uses references for structs and a link transformer is included to add `$schema` fields and links into responses. The `/openapi.[json|yaml]`, `/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 := huma.DefaultConfig("My API", "1.0.0")

// Create the API using the config.
router := chi.NewMux()
api := humachi.New(router, config)

If desired, CBOR (a binary format similar to JSON) support can be automatically enabled by importing the CBOR package:

import _ "github.com/danielgtaylor/huma/v2/formats/cbor"

type Contact

type Contact struct {
	// Name of the contact person/organization.
	Name string `yaml:"name,omitempty"`

	// URL pointing to the contact information.
	URL string `yaml:"url,omitempty"`

	// Email address of the contact person/organization.
	Email string `yaml:"email,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Contact information to get support for the API.

name: API Support
url: https://www.example.com/support
email: support@example.com

func (*Contact) MarshalJSON added in v2.4.0

func (c *Contact) MarshalJSON() ([]byte, error)

type ContentTypeFilter

type ContentTypeFilter interface {
	ContentType(string) string
}

ContentTypeFilter allows you to override the content type for responses, allowing you to return a different content type like `application/problem+json` after using the `application/json` marshaller. This should be implemented by the response body struct.

type Context

type Context interface {
	// Operation returns the OpenAPI operation that matched the request.
	Operation() *Operation

	// Context returns the underlying request context.
	Context() context.Context

	// TLS / SSL connection information.
	TLS() *tls.ConnectionState

	// Version of the HTTP protocol as text and integers.
	Version() ProtoVersion

	// Method returns the HTTP method for the request.
	Method() string

	// Host returns the HTTP host for the request.
	Host() string

	// RemoteAddr returns the remote address of the client.
	RemoteAddr() string

	// URL returns the full URL for the request.
	URL() url.URL

	// Param returns the value for the given path parameter.
	Param(name string) string

	// Query returns the value for the given query parameter.
	Query(name string) string

	// Header returns the value for the given header.
	Header(name string) string

	// EachHeader iterates over all headers and calls the given callback with
	// the header name and value.
	EachHeader(cb func(name, value string))

	// BodyReader returns the request body reader.
	BodyReader() io.Reader

	// GetMultipartForm returns the parsed multipart form, if any.
	GetMultipartForm() (*multipart.Form, error)

	// SetReadDeadline sets the read deadline for the request body.
	SetReadDeadline(time.Time) error

	// SetStatus sets the HTTP status code for the response.
	SetStatus(code int)

	// Status returns the HTTP status code for the response.
	Status() int

	// SetHeader sets the given header to the given value, overwriting any
	// existing value. Use `AppendHeader` to append a value instead.
	SetHeader(name, value string)

	// AppendHeader appends the given value to the given header.
	AppendHeader(name, value string)

	// BodyWriter returns the response body writer.
	BodyWriter() io.Writer
}

Context is the current request/response context. It provides a generic interface to get request information and write responses.

func WithContext added in v2.8.0

func WithContext(ctx Context, override context.Context) Context

WithContext returns a new `huma.Context` with the underlying `context.Context` replaced with the given one. This is useful for middleware that needs to modify the request context.

func WithValue added in v2.8.0

func WithValue(ctx Context, key, value any) Context

WithValue returns a new `huma.Context` with the given key and value set in the underlying `context.Context`. This is useful for middleware that needs to set request-scoped values.

type Discriminator added in v2.15.0

type Discriminator struct {
	// PropertyName in the payload that will hold the discriminator value.
	// REQUIRED.
	PropertyName string `yaml:"propertyName"`

	// Mapping object to hold mappings between payload values and schema names or
	// references.
	Mapping map[string]string `yaml:"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.

func (*Discriminator) MarshalJSON added in v2.15.0

func (d *Discriminator) MarshalJSON() ([]byte, error)

type Encoding

type Encoding struct {
	// ContentType for encoding a specific property. Default value depends on the
	// property type: for object - application/json; for array – the default is
	// defined based on the inner type; for all other cases the default is
	// application/octet-stream. The value can be a specific media type (e.g.
	// application/json), a wildcard media type (e.g. image/*), or a
	// comma-separated list of the two types.
	ContentType string `yaml:"contentType,omitempty"`

	// Headers is a map allowing additional information to be provided as headers,
	// for example Content-Disposition. Content-Type is described separately and
	// SHALL be ignored in this section. This property SHALL be ignored if the
	// request body media type is not a multipart.
	Headers map[string]*Header `yaml:"headers,omitempty"`

	// Style describes how a specific property value will be serialized depending
	// on its type. See Parameter Object for details on the style property. The
	// behavior follows the same values as query parameters, including default
	// values. This property SHALL be ignored if the request body media type is
	// not application/x-www-form-urlencoded or multipart/form-data. If a value is
	// explicitly defined, then the value of contentType (implicit or explicit)
	// SHALL be ignored.
	Style string `yaml:"style,omitempty"`

	// Explode, when true, property values of type array or object generate
	// separate parameters for each value of the array, or key-value-pair of the
	// map. For other types of properties this property has no effect. When style
	// is form, the default value is true. For all other styles, the default value
	// is false. This property SHALL be ignored if the request body media type is
	// not application/x-www-form-urlencoded or multipart/form-data. If a value is
	// explicitly defined, then the value of contentType (implicit or explicit)
	// SHALL be ignored.
	Explode *bool `yaml:"explode,omitempty"`

	// AllowReserved determines whether the parameter value SHOULD allow reserved
	// characters, as defined by [RFC3986] :/?#[]@!$&'()*+,;= to be included
	// without percent-encoding. The default value is false. This property SHALL
	// be ignored if the request body media type is not
	// application/x-www-form-urlencoded or multipart/form-data. If a value is
	// explicitly defined, then the value of contentType (implicit or explicit)
	// SHALL be ignored.
	AllowReserved bool `yaml:"allowReserved,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Encoding is a single encoding definition applied to a single schema property.

requestBody:
  content:
    multipart/form-data:
      schema:
        type: object
        properties:
          id:
            # default is text/plain
            type: string
            format: uuid
          address:
            # default is application/json
            type: object
            properties: {}
          historyMetadata:
            # need to declare XML format!
            description: metadata in XML format
            type: object
            properties: {}
          profileImage: {}
      encoding:
        historyMetadata:
          # require XML Content-Type in utf-8 encoding
          contentType: application/xml; charset=utf-8
        profileImage:
          # only accept png/jpeg
          contentType: image/png, image/jpeg
          headers:
            X-Rate-Limit-Limit:
              description: The number of allowed requests in the current period
              schema:
                type: integer

func (*Encoding) MarshalJSON added in v2.4.0

func (e *Encoding) MarshalJSON() ([]byte, error)

type ErrorDetail

type ErrorDetail struct {
	// Message is a human-readable explanation of the error.
	Message string `json:"message,omitempty" doc:"Error message text"`

	// Location is a path-like string indicating where the error occurred.
	// It typically begins with `path`, `query`, `header`, or `body`. Example:
	// `body.items[3].tags` or `path.thing-id`.
	Location string `json:"location,omitempty" doc:"Where the error occurred, e.g. 'body.items[3].tags' or 'path.thing-id'"`

	// Value is the value at the given location, echoed back to the client
	// to help with debugging. This can be useful for e.g. validating that
	// the client didn't send extra whitespace or help when the client
	// did not log an outgoing request.
	Value any `json:"value,omitempty" doc:"The value at the given location"`
}

ErrorDetail provides details about a specific error.

func (*ErrorDetail) Error

func (e *ErrorDetail) Error() string

Error returns the error message / satisfies the `error` interface. If a location and value are set, they will be included in the error message, otherwise just the message is returned.

func (*ErrorDetail) ErrorDetail

func (e *ErrorDetail) ErrorDetail() *ErrorDetail

ErrorDetail satisfies the `ErrorDetailer` interface.

type 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 `` /* 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 `` /* 166-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 occurrence.
	Instance string `` /* 163-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 based on RFC 9457 Problem Details for HTTP APIs (https://datatracker.ietf.org/doc/html/rfc9457). It is augmented with an `errors` field of `huma.ErrorDetail` objects that can help provide exhaustive & descriptive errors.

err := &huma.ErrorModel{
	Title: http.StatusText(http.StatusBadRequest),
	Status http.StatusBadRequest,
	Detail: "Validation failed",
	Errors: []*huma.ErrorDetail{
		&huma.ErrorDetail{
			Message: "expected required property id to be present",
			Location: "body.friends[0]",
			Value: nil,
		},
		&huma.ErrorDetail{
			Message: "expected boolean",
			Location: "body.friends[1].active",
			Value: 5,
		},
	},
}

func (*ErrorModel) Add

func (e *ErrorModel) Add(err error)

Add an error to the `Errors` slice. If passed a struct that satisfies the `huma.ErrorDetailer` interface, then it is used, otherwise the error string is used as the error detail message.

err := &ErrorModel{ /* ... */ }
err.Add(&huma.ErrorDetail{
	Message: "expected boolean",
	Location: "body.friends[1].active",
	Value: 5
})

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 `yaml:"$ref,omitempty"`

	// Summary is a short summary of the example.
	Summary string `yaml:"summary,omitempty"`

	// Description is a long description of the example. CommonMark syntax MAY
	// be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Value is an embedded literal example. The `value` field and `externalValue`
	// field are mutually exclusive. To represent examples of media types that
	// cannot naturally represented in JSON or YAML, use a string value to contain
	// the example, escaping where necessary.
	Value any `yaml:"value,omitempty"`

	// ExternalValue is a URI that points to the literal example. This provides
	// the capability to reference examples that cannot easily be included in JSON
	// or YAML documents. The `value` field and `externalValue` field are mutually
	// exclusive. See the rules for resolving Relative References.
	ExternalValue string `yaml:"externalValue,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Example value of a request param or body or response header or body.

requestBody:
  content:
    'application/json':
      schema:
        $ref: '#/components/schemas/Address'
      examples:
        foo:
          summary: A foo example
          value: {"foo": "bar"}
        bar:
          summary: A bar example
          value: {"bar": "baz"}

func (*Example) MarshalJSON added in v2.4.0

func (e *Example) MarshalJSON() ([]byte, error)

type ExternalDocs

type ExternalDocs struct {
	// Description of the target documentation. CommonMark syntax MAY be used for
	// rich text representation.
	Description string `yaml:"description,omitempty"`

	// URL is REQUIRED. The URL for the target documentation. Value MUST be in the
	// format of a URL.
	URL string `yaml:"url"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

ExternalDocs allows referencing an external resource for extended documentation.

description: Find more info here
url: https://example.com

func (*ExternalDocs) MarshalJSON added in v2.4.0

func (e *ExternalDocs) MarshalJSON() ([]byte, error)

type FormFile added in v2.18.0

type FormFile struct {
	multipart.File
	ContentType string // Content-Type as declared in the multipart form field, or detected when parsing request as fallback
	IsSet       bool   // Indicates whether content was received when working with optional files
	Size        int64  // File size in bytes
	Filename    string // Filename as declared in the multipart form field, if any
}

type Format

type Format struct {
	// Marshal a value to a given writer (e.g. response body).
	Marshal func(writer io.Writer, v any) error

	// Unmarshal a value into `v` from the given bytes (e.g. request body).
	Unmarshal func(data []byte, v any) error
}

Format represents a request / response format. It is used to marshal and unmarshal data.

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 added in v2.14.0

type HeadersError interface {
	GetHeaders() http.Header
	Error() string
}

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 `huma.Error400BadRequest` with additional headers.

type Info

type Info struct {
	// Title of the API.
	Title string `yaml:"title"`

	// Description of the API. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// TermsOfService URL for the API.
	TermsOfService string `yaml:"termsOfService,omitempty"`

	// Contact information to get support for the API.
	Contact *Contact `yaml:"contact,omitempty"`

	// License name & link for using the API.
	License *License `yaml:"license,omitempty"`

	// Version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).
	Version string `yaml:"version"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

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

title: Sample Pet Store App
summary: A pet store manager.
description: This is a sample server for a pet store.
termsOfService: https://example.com/terms/
contact:
  name: API Support
  url: https://www.example.com/support
  email: support@example.com
license:
  name: Apache 2.0
  url: https://www.apache.org/licenses/LICENSE-2.0.html
version: 1.0.1

func (*Info) MarshalJSON added in v2.4.0

func (i *Info) MarshalJSON() ([]byte, error)

type License

type License struct {
	// Name of the license.
	Name string `yaml:"name"`

	// Identifier SPDX license expression for the API. This field is mutually
	// exclusive with the URL field.
	Identifier string `yaml:"identifier,omitempty"`

	// URL pointing to the license. This field is mutually exclusive with the
	// Identifier field.
	URL string `yaml:"url,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

License name & link for using the API.

name: Apache 2.0
identifier: Apache-2.0

func (*License) MarshalJSON added in v2.4.0

func (l *License) MarshalJSON() ([]byte, error)
type Link struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// OperationRef is a relative or absolute URI reference to an OAS operation.
	// This field is mutually exclusive of the operationId field, and MUST point
	// to an Operation Object. Relative operationRef values MAY be used to locate
	// an existing Operation Object in the OpenAPI definition. See the rules for
	// resolving Relative References.
	OperationRef string `yaml:"operationRef,omitempty"`

	// OperationID is the name of an existing, resolvable OAS operation, as
	// defined with a unique operationId. This field is mutually exclusive of the
	// operationRef field.
	OperationID string `yaml:"operationId,omitempty"`

	// Parameters is a map representing parameters to pass to an operation as
	// specified with operationId or identified via operationRef. The key is the
	// parameter name to be used, whereas the value can be a constant or an
	// expression to be evaluated and passed to the linked operation. The
	// parameter name can be qualified using the parameter location [{in}.]{name}
	// for operations that use the same parameter name in different locations
	// (e.g. path.id).
	Parameters map[string]any `yaml:"parameters,omitempty"`

	// RequestBody is a literal value or {expression} to use as a request body
	// when calling the target operation.
	RequestBody any `yaml:"requestBody,omitempty"`

	// Description of the link. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Server object to be used by the target operation.
	Server *Server `yaml:"server,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Link object represents a possible design-time link for a response. The presence of a link does not guarantee the caller’s ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations.

Unlike dynamic links (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response.

For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.

paths:
  /users/{id}:
    parameters:
    - name: id
      in: path
      required: true
      description: the user identifier, as userId
      schema:
        type: string
    get:
      responses:
        '200':
          description: the user being returned
          content:
            application/json:
              schema:
                type: object
                properties:
                  uuid: # the unique user id
                    type: string
                    format: uuid
          links:
            address:
              # the target link operationId
              operationId: getUserAddress
              parameters:
                # get the `id` field from the request path parameter named `id`
                userId: $request.path.id
  # the path item of the linked operation
  /users/{userid}/address:
    parameters:
    - name: userid
      in: path
      required: true
      description: the user identifier, as userId
      schema:
        type: string
    # linked operation
    get:
      operationId: getUserAddress
      responses:
        '200':
          description: the user's address

func (*Link) MarshalJSON added in v2.4.0

func (l *Link) MarshalJSON() ([]byte, error)

type MediaType

type MediaType struct {
	// Schema defining the content of the request, response, or parameter.
	Schema *Schema `yaml:"schema,omitempty"`

	// Example of the media type. The example object SHOULD be in the correct
	// format as specified by the media type. The example field is mutually
	// exclusive of the examples field. Furthermore, if referencing a schema which
	// contains an example, the example value SHALL override the example provided
	// by the schema.
	Example any `yaml:"example,omitempty"`

	// Examples of the media type. Each example object SHOULD match the media type
	// and specified schema if present. The examples field is mutually exclusive
	// of the example field. Furthermore, if referencing a schema which contains
	// an example, the examples value SHALL override the example provided by the
	// schema.
	Examples map[string]*Example `yaml:"examples,omitempty"`

	// Encoding is a map between a property name and its encoding information. The
	// key, being the property name, MUST exist in the schema as a property. The
	// encoding object SHALL only apply to requestBody objects when the media type
	// is multipart or application/x-www-form-urlencoded.
	Encoding map[string]*Encoding `yaml:"encoding,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

MediaType object provides schema and examples for the media type identified by its key.

application/json:
  schema:
    $ref: "#/components/schemas/Pet"
  examples:
    cat:
      summary: An example of a cat
      value:
        name: Fluffy
        petType: Cat
        color: White
        gender: male
        breed: Persian

func (*MediaType) MarshalJSON added in v2.4.0

func (m *MediaType) MarshalJSON() ([]byte, error)

type Middlewares

type Middlewares []func(ctx Context, next func(Context))

Middlewares is a list of middleware functions that can be attached to an API and will be called for all incoming requests.

func (Middlewares) Handler

func (m Middlewares) Handler(endpoint func(Context)) func(Context)

Handler builds and returns a handler func from the chain of middlewares, with `endpoint func` as the final handler.

type MimeTypeValidator added in v2.18.0

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

func NewMimeTypeValidator added in v2.18.0

func NewMimeTypeValidator(encoding *Encoding) MimeTypeValidator

func (MimeTypeValidator) Validate added in v2.18.0

func (v MimeTypeValidator) Validate(fh *multipart.FileHeader, location string) (string, *ErrorDetail)

Validate checks the mime type of the provided file against the expected content type. In the absence of a Content-Type file header, the mime type is detected using http.DetectContentType.

type ModelValidator

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

ModelValidator is a utility for validating e.g. JSON loaded data against a Go struct model. It is not goroutine-safe and should not be used in HTTP handlers! Schemas are generated on-the-fly on first use and re-used on subsequent calls. This utility can be used to easily validate data outside of the normal request/response flow, for example on application startup:

type MyExample struct {
	Name string `json:"name" maxLength:"5"`
	Age int `json:"age" minimum:"25"`
}

var value any
json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &value)

validator := ModelValidator()
errs := validator.Validate(reflect.TypeOf(MyExample{}), value)
if errs != nil {
	fmt.Println("Validation error", errs)
}
Example
// Define a type you want to validate.
type Model struct {
	Name string `json:"name" maxLength:"5"`
	Age  int    `json:"age" minimum:"25"`
}

typ := reflect.TypeOf(Model{})

// Unmarshal some JSON into an `any` for validation. This input should not
// validate against the schema for the struct above.
var val any
json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &val)

// Validate the unmarshaled data against the type and print errors.
validator := huma.NewModelValidator()
errs := validator.Validate(typ, val)
fmt.Println(errs)

// Try again with valid data!
json.Unmarshal([]byte(`{"name": "foo", "age": 25}`), &val)
errs = validator.Validate(typ, val)
fmt.Println(errs)
Output:

[expected number >= 25 (age: 1) expected length <= 5 (name: abcdefg)]
[]

func NewModelValidator

func NewModelValidator() *ModelValidator

NewModelValidator creates a new model validator with all the components it needs to create schemas, validate them, and return any errors.

func (*ModelValidator) Validate

func (v *ModelValidator) Validate(typ reflect.Type, value any) []error

Validate the inputs. The type should be the Go struct with validation field tags and the value should be e.g. JSON loaded into an `any`. A list of errors is returned if validation failed, otherwise `nil`.

type MyExample struct {
	Name string `json:"name" maxLength:"5"`
	Age int `json:"age" minimum:"25"`
}

var value any
json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &value)

validator := ModelValidator()
errs := validator.Validate(reflect.TypeOf(MyExample{}), value)
if errs != nil {
	fmt.Println("Validation error", errs)
}

type MultipartFormFiles added in v2.18.0

type MultipartFormFiles[T any] struct {
	Form *multipart.Form
	// contains filtered or unexported fields
}

func (*MultipartFormFiles[T]) Data added in v2.18.0

func (m *MultipartFormFiles[T]) Data() *T

func (*MultipartFormFiles[T]) Decode added in v2.18.0

func (m *MultipartFormFiles[T]) Decode(opMediaType *MediaType) []error

Decodes multipart.Form data into *T, returning []*ErrorDetail if any Schema is used to check for validation constraints

type OAuthFlow

type OAuthFlow struct {
	// AuthorizationURL is REQUIRED for `implicit` and `authorizationCode` flows.
	// The authorization URL to be used for this flow. This MUST be in the form of
	// a URL. The OAuth2 standard requires the use of TLS.
	AuthorizationURL string `yaml:"authorizationUrl,omitempty"`

	// TokenURL is REQUIRED. The token URL to be used for this flow. This MUST be
	// in the form of a URL. The OAuth2 standard requires the use of TLS.
	TokenURL string `yaml:"tokenUrl"`

	// RefreshURL is the URL to be used for obtaining refresh tokens. This MUST be
	// in the form of a URL. The OAuth2 standard requires the use of TLS.
	RefreshURL string `yaml:"refreshUrl,omitempty"`

	// Scopes are REQUIRED. The available scopes for the OAuth2 security scheme. A
	// map between the scope name and a short description for it. The map MAY be
	// empty.
	Scopes map[string]string `yaml:"scopes"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

OAuthFlow stores configuration details for a supported OAuth Flow.

type: oauth2
flows:
  implicit:
    authorizationUrl: https://example.com/api/oauth/dialog
    scopes:
      write:pets: modify pets in your account
      read:pets: read your pets
  authorizationCode:
    authorizationUrl: https://example.com/api/oauth/dialog
    tokenUrl: https://example.com/api/oauth/token
    scopes:
      write:pets: modify pets in your account
      read:pets: read your pets

func (*OAuthFlow) MarshalJSON added in v2.4.0

func (o *OAuthFlow) MarshalJSON() ([]byte, error)

type OAuthFlows

type OAuthFlows struct {
	// Implicit is the configuration for the OAuth Implicit flow.
	Implicit *OAuthFlow `yaml:"implicit,omitempty"`

	// Password is the configuration for the OAuth Resource Owner Password flow.
	Password *OAuthFlow `yaml:"password,omitempty"`

	// ClientCredentials is the configuration for the OAuth Client Credentials
	// flow. Previously called application in OpenAPI 2.0.
	ClientCredentials *OAuthFlow `yaml:"clientCredentials,omitempty"`

	// AuthorizationCode is the configuration for the OAuth Authorization Code
	// flow. Previously called accessCode in OpenAPI 2.0.
	AuthorizationCode *OAuthFlow `yaml:"authorizationCode,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

OAuthFlows allows configuration of the supported OAuth Flows.

func (*OAuthFlows) MarshalJSON added in v2.4.0

func (o *OAuthFlows) MarshalJSON() ([]byte, error)

type OpenAPI

type OpenAPI struct {
	// OpenAPI is REQUIRED. This string MUST be the version number of the OpenAPI
	// Specification that the OpenAPI document uses. The openapi field SHOULD be
	// used by tooling to interpret the OpenAPI document. This is not related to
	// the API info.version string.
	OpenAPI string `yaml:"openapi"`

	// Info is REQUIRED. Provides metadata about the API. The metadata MAY be used
	// by tooling as required.
	Info *Info `yaml:"info"`

	// JSONSchemaDialect is the default value for the $schema keyword within Schema
	// Objects contained within this OAS document. This MUST be in the form of a
	// URI.
	JSONSchemaDialect string `yaml:"jsonSchemaDialect,omitempty"`

	// Servers is an array of Server Objects, which provide connectivity
	// information to a target server. If the servers property is not provided, or
	// is an empty array, the default value would be a Server Object with a url
	// value of /.
	Servers []*Server `yaml:"servers,omitempty"`

	// Paths are the available paths and operations for the API.
	Paths map[string]*PathItem `yaml:"paths,omitempty"`

	// Webhooks that MAY be received as part of this API and that the API consumer
	// MAY choose to implement. Closely related to the callbacks feature, this
	// section describes requests initiated other than by an API call, for example
	// by an out of band registration. The key name is a unique string to refer to
	// each webhook, while the (optionally referenced) Path Item Object describes
	// a request that may be initiated by the API provider and the expected
	// responses. An example is available.
	Webhooks map[string]*PathItem `yaml:"webhooks,omitempty"`

	// Components is an element to hold various schemas for the document.
	Components *Components `yaml:"components,omitempty"`

	// Security is a declaration of which security mechanisms can be used across
	// the API. The list of values includes alternative security requirement
	// objects that can be used. Only one of the security requirement objects need
	// to be satisfied to authorize a request. Individual operations can override
	// this definition. To make security optional, an empty security requirement
	// ({}) can be included in the array.
	Security []map[string][]string `yaml:"security,omitempty"`

	// Tags are a list of tags used by the document with additional metadata. The
	// order of the tags can be used to reflect on their order by the parsing
	// tools. Not all tags that are used by the Operation Object must be declared.
	// The tags that are not declared MAY be organized randomly or based on the
	// tools’ logic. Each tag name in the list MUST be unique.
	Tags []*Tag `yaml:"tags,omitempty"`

	// ExternalDocs is additional external documentation.
	ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`

	// OnAddOperation is called when an operation is added to the OpenAPI via
	// `AddOperation`. You may bypass this by directly writing to the `Paths`
	// map instead.
	OnAddOperation []AddOpFunc `yaml:"-"`
}

OpenAPI is the root object of the OpenAPI document.

func (*OpenAPI) AddOperation

func (o *OpenAPI) AddOperation(op *Operation)

AddOperation adds an operation to the OpenAPI. This is the preferred way to add operations to the OpenAPI, as it will ensure that the operation is properly added to the Paths map, and will call any registered OnAddOperation functions.

func (OpenAPI) Downgrade added in v2.12.0

func (o OpenAPI) Downgrade() ([]byte, error)

Downgrade converts this OpenAPI 3.1 spec to OpenAPI 3.0.3, returning the JSON []byte representation of the downgraded spec. This mostly exists to provide an alternative spec for tools which are not yet 3.1 compatible.

It reverses the changes documented at: https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0

func (*OpenAPI) DowngradeYAML added in v2.12.0

func (o *OpenAPI) DowngradeYAML() ([]byte, error)

DowngradeYAML converts this OpenAPI 3.1 spec to OpenAPI 3.0.3, returning the YAML []byte representation of the downgraded spec.

func (*OpenAPI) MarshalJSON

func (o *OpenAPI) MarshalJSON() ([]byte, error)

func (*OpenAPI) YAML added in v2.4.0

func (o *OpenAPI) YAML() ([]byte, error)

YAML returns the OpenAPI represented as YAML without needing to include a library to serialize YAML.

type Operation

type Operation struct {

	// Method is the HTTP method for this operation
	Method string `yaml:"-"`

	// Path is the URL path for this operation
	Path string `yaml:"-"`

	// 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 `yaml:"-"`

	// MaxBodyBytes is the maximum number of bytes to read from the request
	// body. If not specified, the default is 1MB. Use -1 for unlimited. If
	// the limit is reached, then an HTTP 413 error is returned.
	MaxBodyBytes int64 `yaml:"-"`

	// BodyReadTimeout is the maximum amount of time to wait for the request
	// body to be read. If not specified, the default is 5 seconds. Use -1
	// for unlimited. If the timeout is reached, then an HTTP 408 error is
	// returned. This value supersedes the server's read timeout, and a value
	// of -1 can unset the server's timeout.
	BodyReadTimeout time.Duration `yaml:"-"`

	// 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 `huma.NewError()`
	// or `huma.NewErrorWithContext`.
	Errors []int `yaml:"-"`

	// SkipValidateParams disables validation of path, query, and header
	// parameters. This can speed up request processing if you want to handle
	// your own validation. Use with caution!
	SkipValidateParams bool `yaml:"-"`

	// SkipValidateBody disables validation of the request body. This can speed
	// up request processing if you want to handle your own validation. Use with
	// caution!
	SkipValidateBody bool `yaml:"-"`

	// Hidden will skip documenting this operation in the OpenAPI. This is
	// useful for operations that are not intended to be used by clients but
	// you'd still like the benefits of using Huma. Generally not recommended.
	Hidden bool `yaml:"-"`

	// Metadata is a map of arbitrary data that can be attached to the operation.
	// This can be used to store custom data, such as custom settings for
	// functions which generate operations.
	Metadata map[string]any `yaml:"-"`

	// 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 `yaml:"-"`

	// Tags is a list of tags for API documentation control. Tags can be used for
	// logical grouping of operations by resources or any other qualifier.
	Tags []string `yaml:"tags,omitempty"`

	// Summary is a short summary of what the operation does.
	Summary string `yaml:"summary,omitempty"`

	// Description is a verbose explanation of the operation behavior. CommonMark
	// syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// ExternalDocs describes additional external documentation for this
	// operation.
	ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`

	// OperationID is a unique string used to identify the operation. The id MUST
	// be unique among all operations described in the API. The operationId value
	// is case-sensitive. Tools and libraries MAY use the operationId to uniquely
	// identify an operation, therefore, it is RECOMMENDED to follow common
	// programming naming conventions.
	OperationID string `yaml:"operationId,omitempty"`

	// Parameters is a list of parameters that are applicable for this operation.
	// If a parameter is already defined at the Path Item, the new definition will
	// override it but can never remove it. The list MUST NOT include duplicated
	// parameters. A unique parameter is defined by a combination of a name and
	// location. The list can use the Reference Object to link to parameters that
	// are defined at the OpenAPI Object’s components/parameters.
	Parameters []*Param `yaml:"parameters,omitempty"`

	// RequestBody applicable for this operation. The requestBody is fully
	// supported in HTTP methods where the HTTP 1.1 specification [RFC7231] has
	// explicitly defined semantics for request bodies. In other cases where the
	// HTTP spec is vague (such as GET, HEAD and DELETE), requestBody is permitted
	// but does not have well-defined semantics and SHOULD be avoided if possible.
	RequestBody *RequestBody `yaml:"requestBody,omitempty"`

	// Responses is the list of possible responses as they are returned from
	// executing this operation.
	Responses map[string]*Response `yaml:"responses,omitempty"`

	// Callbacks is a map of possible out-of band callbacks related to the parent
	// operation. The key is a unique identifier for the Callback Object. Each
	// value in the map is a Callback Object that describes a request that may be
	// initiated by the API provider and the expected responses.
	Callbacks map[string]*PathItem `yaml:"callbacks,omitempty"`

	// Deprecated declares this operation to be deprecated. Consumers SHOULD
	// refrain from usage of the declared operation. Default value is false.
	Deprecated bool `yaml:"deprecated,omitempty"`

	// Security is a declaration of which security mechanisms can be used for this
	// operation. The list of values includes alternative security requirement
	// objects that can be used. Only one of the security requirement objects need
	// to be satisfied to authorize a request. To make security optional, an empty
	// security requirement ({}) can be included in the array. This definition
	// overrides any declared top-level security. To remove a top-level security
	// declaration, an empty array can be used.
	Security []map[string][]string `yaml:"security,omitempty"`

	// Servers is an alternative server array to service this operation. If an
	// alternative server object is specified at the Path Item Object or Root
	// level, it will be overridden by this value.
	Servers []*Server `yaml:"servers,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Operation describes a single API operation on a path.

tags:
- pet
summary: Updates a pet in the store with form data
operationId: updatePetWithForm
parameters:
- name: petId
  in: path
  description: ID of pet that needs to be updated
  required: true
  schema:
    type: string
requestBody:
  content:
    'application/x-www-form-urlencoded':
      schema:
       type: object
       properties:
          name:
            description: Updated name of the pet
            type: string
          status:
            description: Updated status of the pet
            type: string
       required:
         - status
responses:
  '200':
    description: Pet updated.
    content:
      'application/json': {}
      'application/xml': {}
  '405':
    description: Method Not Allowed
    content:
      'application/json': {}
      'application/xml': {}
security:
- petstore_auth:
  - write:pets
  - read:pets

func (*Operation) MarshalJSON added in v2.4.0

func (o *Operation) MarshalJSON() ([]byte, error)

type Param

type Param struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

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

	// In is REQUIRED. The location of the parameter. Possible values are "query",
	// "header", "path" or "cookie".
	In string `yaml:"in,omitempty"`

	// Description of the parameter. This could contain examples of use.
	// CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Required determines whether this parameter is mandatory. If the parameter
	// location is "path", this property is REQUIRED and its value MUST be true.
	// Otherwise, the property MAY be included and its default value is false.
	Required bool `yaml:"required,omitempty"`

	// Deprecated specifies that a parameter is deprecated and SHOULD be
	// transitioned out of usage. Default value is false.
	Deprecated bool `yaml:"deprecated,omitempty"`

	// AllowEmptyValue sets the ability to pass empty-valued parameters. This is
	// valid only for query parameters and allows sending a parameter with an
	// empty value. Default value is false. If style is used, and if behavior is
	// n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored.
	// Use of this property is NOT RECOMMENDED, as it is likely to be removed in a
	// later revision.
	AllowEmptyValue bool `yaml:"allowEmptyValue,omitempty"`

	// Style describes how the parameter value will be serialized depending on the
	// type of the parameter value. Default values (based on value of in): for
	// query - form; for path - simple; for header - simple; for cookie - form.
	Style string `yaml:"style,omitempty"`

	// Explode, when true, makes parameter values of type array or object generate
	// separate parameters for each value of the array or key-value pair of the
	// map. For other types of parameters this property has no effect. When style
	// is form, the default value is true. For all other styles, the default value
	// is false.
	Explode *bool `yaml:"explode,omitempty"`

	// AllowReserved determines whether the parameter value SHOULD allow reserved
	// characters, as defined by [RFC3986] :/?#[]@!$&'()*+,;= to be included
	// without percent-encoding. This property only applies to parameters with an
	// in value of query. The default value is false.
	AllowReserved bool `yaml:"allowReserved,omitempty"`

	// Schema defining the type used for the parameter.
	Schema *Schema `yaml:"schema,omitempty"`

	// Example of the parameter’s potential value. The example SHOULD match the
	// specified schema and encoding properties if present. The example field is
	// mutually exclusive of the examples field. Furthermore, if referencing a
	// schema that contains an example, the example value SHALL override the
	// example provided by the schema. To represent examples of media types that
	// cannot naturally be represented in JSON or YAML, a string value can contain
	// the example with escaping where necessary.
	Example any `yaml:"example,omitempty"`

	// Examples of the parameter’s potential value. Each example SHOULD contain a
	// value in the correct format as specified in the parameter encoding. The
	// examples field is mutually exclusive of the example field. Furthermore, if
	// referencing a schema that contains an example, the examples value SHALL
	// override the example provided by the schema.
	Examples map[string]*Example `yaml:"examples,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Param Describes a single operation parameter.

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

name: username
in: path
description: username to fetch
required: true
schema:
  type: string

func (*Param) MarshalJSON added in v2.4.0

func (p *Param) MarshalJSON() ([]byte, error)

type PathBuffer

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

PathBuffer is a low-allocation helper for building a path string like `foo.bar.baz`. It is not goroutine-safe. Combined with `sync.Pool` it can result in zero allocations, and is used for validation. It is significantly better than `strings.Builder` and `bytes.Buffer` for this use case.

Path buffers can be converted to strings for use in responses or printing using either the `pb.String()` or `pb.With("field")` methods.

pb := NewPathBuffer([]byte{}, 0)
pb.Push("foo")  // foo
pb.PushIndex(1) // foo[1]
pb.Push("bar")  // foo[1].bar
pb.Pop()        // foo[1]
pb.Pop()        // foo

func NewPathBuffer

func NewPathBuffer(buf []byte, offset int) *PathBuffer

NewPathBuffer creates a new path buffer given an existing byte slice. Tip: using `sync.Pool` can significantly reduce buffer allocations.

pb := NewPathBuffer([]byte{}, 0)
pb.Push("foo")

func (*PathBuffer) Bytes

func (b *PathBuffer) Bytes() []byte

Bytes returns the underlying slice of bytes of the path.

func (*PathBuffer) Len

func (b *PathBuffer) Len() int

Len returns the length of the current path.

func (*PathBuffer) Pop

func (b *PathBuffer) Pop()

Pop the latest entry off the path.

pb.Push("foo")  // foo
pb.PushIndex(1) // foo[1]
pb.Push("bar")  // foo[1].bar
pb.Pop()        // foo[1]
pb.Pop()        // foo

func (*PathBuffer) Push

func (b *PathBuffer) Push(s string)

Push an entry onto the path, adding a `.` separator as needed.

pb.Push("foo") // foo
pb.Push("bar") // foo.bar

func (*PathBuffer) PushIndex

func (b *PathBuffer) PushIndex(i int)

PushIndex pushes an entry onto the path surrounded by `[` and `]`.

pb.Push("foo")  // foo
pb.PushIndex(1) // foo[1]

func (*PathBuffer) Reset

func (b *PathBuffer) Reset()

Reset the path buffer to empty, keeping and reusing the underlying bytes.

func (*PathBuffer) String

func (b *PathBuffer) String() string

String converts the path buffer to a string.

func (*PathBuffer) With

func (b *PathBuffer) With(s string) string

With is shorthand for push, convert to string, and pop. This is useful when you want the location of a field given a path buffer as a prefix.

pb.Push("foo")
pb.With("bar") // returns foo.bar

type PathItem

type PathItem struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// Summary is an optional, string summary, intended to apply to all operations
	// in this path.
	Summary string `yaml:"summary,omitempty"`

	// Description is an optional, string description, intended to apply to all
	// operations in this path. CommonMark syntax MAY be used for rich text
	// representation.
	Description string `yaml:"description,omitempty"`

	// Get is a definition of a GET operation on this path.
	Get *Operation `yaml:"get,omitempty"`

	// Put is a definition of a PUT operation on this path.
	Put *Operation `yaml:"put,omitempty"`

	// Post is a definition of a POST operation on this path.
	Post *Operation `yaml:"post,omitempty"`

	// Delete is a definition of a DELETE operation on this path.
	Delete *Operation `yaml:"delete,omitempty"`

	// Options is a definition of a OPTIONS operation on this path.
	Options *Operation `yaml:"options,omitempty"`

	// Head is a definition of a HEAD operation on this path.
	Head *Operation `yaml:"head,omitempty"`

	// Patch is a definition of a PATCH operation on this path.
	Patch *Operation `yaml:"patch,omitempty"`

	// Trace is a definition of a TRACE operation on this path.
	Trace *Operation `yaml:"trace,omitempty"`

	// Servers is an alternative server array to service all operations in this
	// path.
	Servers []*Server `yaml:"servers,omitempty"`

	// Parameters is a list of parameters that are applicable for all the
	// operations described under this path. These parameters can be overridden at
	// the operation level, but cannot be removed there. The list MUST NOT include
	// duplicated parameters. A unique parameter is defined by a combination of a
	// name and location. The list can use the Reference Object to link to
	// parameters that are defined at the OpenAPI Object’s components/parameters.
	Parameters []*Param `yaml:"parameters,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

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

get:
  description: Returns pets based on ID
  summary: Find pets by ID
  operationId: getPetsById
  responses:
    '200':
      description: pet response
      content:
        '*/*' :
          schema:
            type: array
            items:
              $ref: '#/components/schemas/Pet'
    default:
      description: error payload
      content:
        'text/html':
          schema:
            $ref: '#/components/schemas/ErrorModel'
parameters:
- name: id
  in: path
  description: ID of pet to use
  required: true
  schema:
    type: array
    items:
      type: string
  style: simple

func (*PathItem) MarshalJSON added in v2.4.0

func (p *PathItem) MarshalJSON() ([]byte, error)

type ProtoVersion added in v2.24.0

type ProtoVersion struct {
	Proto      string
	ProtoMajor int
	ProtoMinor int
}

Represent http protocol version

type Registry

type Registry interface {
	Schema(t reflect.Type, allowRef bool, hint string) *Schema
	SchemaFromRef(ref string) *Schema
	TypeFromRef(ref string) reflect.Type
	Map() map[string]*Schema
	RegisterTypeAlias(t reflect.Type, alias reflect.Type)
}

Registry creates and stores schemas and their references, and supports marshalling to JSON/YAML for use as an OpenAPI #/components/schemas object. Behavior is implementation-dependent, but the design allows for recursive schemas to exist while being flexible enough to support other use cases like only inline objects (no refs) or always using refs for structs.

func NewMapRegistry

func NewMapRegistry(prefix string, namer func(t reflect.Type, hint string) string) Registry

NewMapRegistry creates a new registry that stores schemas in a map and returns references to them using the given prefix.

type RequestBody

type RequestBody struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// Description of the request body. This could contain examples of use.
	// CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Content is REQUIRED. The content of the request body. The key is a media
	// type or media type range and the value describes it. For requests that
	// match multiple keys, only the most specific key is applicable. e.g.
	// text/plain overrides text/*
	Content map[string]*MediaType `yaml:"content"`

	// Required Determines if the request body is required in the request.
	// Defaults to false.
	Required bool `yaml:"required,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

RequestBody describes a single request body.

description: user to add to the system
content:
  'application/json':
    schema:
      $ref: '#/components/schemas/User'
    examples:
      user:
        summary: User Example
        externalValue: 'https://foo.bar/examples/user-example.json'

func (*RequestBody) MarshalJSON added in v2.4.0

func (r *RequestBody) MarshalJSON() ([]byte, error)

type Resolver

type Resolver interface {
	Resolve(ctx Context) []error
}

Resolver runs a `Resolve` function after a request has been parsed, enabling you to run custom validation or other code that can modify the request and / or return errors.

Example
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/danielgtaylor/huma/v2"
	"github.com/go-chi/chi/v5"
)

// Step 1: Create your input struct where you want to do additional validation.
// This struct must implement the `huma.Resolver` interface.
type ExampleInputBody struct {
	Count int `json:"count" minimum:"0"`
}

func (b *ExampleInputBody) Resolve(ctx huma.Context, prefix *huma.PathBuffer) []error {
	// Return an error if some arbitrary rule is broken. In this case, if it's
	// a multiple of 30 we return an error.
	if b.Count%30 == 0 {
		return []error{&huma.ErrorDetail{
			Location: prefix.With("count"),
			Message:  "multiples of 30 are not allowed",
			Value:    b.Count,
		}}
	}

	return nil
}

func main() {
	// Create the API.
	r := chi.NewRouter()
	api := NewExampleAPI(r, huma.DefaultConfig("Example API", "1.0.0"))

	huma.Register(api, huma.Operation{
		OperationID: "resolver-example",
		Method:      http.MethodPut,
		Path:        "/resolver",
	}, func(ctx context.Context, input *struct {
		// Step 2: Use your custom struct with the resolver as a field in the
		// request input. Here we use it as the body of the request.
		Body ExampleInputBody
	}) (*struct{}, error) {
		// Do nothing. Validation should catch the error!
		return nil, nil
	})

	// Make an example request showing the validation error response.
	req, _ := http.NewRequest(http.MethodPut, "/resolver", strings.NewReader(`{"count": 30}`))
	req.Host = "example.com"
	req.Header.Set("Content-Type", "application/json")

	w := httptest.NewRecorder()

	r.ServeHTTP(w, req)

	out := bytes.NewBuffer(nil)
	json.Indent(out, w.Body.Bytes(), "", "  ")
	fmt.Println(out.String())
}
Output:

{
  "$schema": "https://example.com/schemas/ErrorModel.json",
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "validation failed",
  "errors": [
    {
      "message": "multiples of 30 are not allowed",
      "location": "body.count",
      "value": 30
    }
  ]
}

type ResolverWithPath

type ResolverWithPath interface {
	Resolve(ctx Context, prefix *PathBuffer) []error
}

ResolverWithPath runs a `Resolve` function after a request has been parsed, enabling you to run custom validation or other code that can modify the request and / or return errors. The `prefix` is the path to the current location for errors, e.g. `body.foo[0].bar`.

type Response

type Response struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// Description is REQUIRED. A description of the response. CommonMark syntax
	// MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Headers maps a header name to its definition. [RFC7230] states header names
	// are case insensitive. If a response header is defined with the name
	// "Content-Type", it SHALL be ignored.
	Headers map[string]*Param `yaml:"headers,omitempty"`

	// Content is a map containing descriptions of potential response payloads.
	// The key is a media type or media type range and the value describes it. For
	// responses that match multiple keys, only the most specific key is
	// applicable. e.g. text/plain overrides text/*
	Content map[string]*MediaType `yaml:"content,omitempty"`

	// Links is a map of operations links that can be followed from the response.
	// The key of the map is a short name for the link, following the naming
	// constraints of the names for Component Objects.
	Links map[string]*Link `yaml:"links,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

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

description: A complex object array response
content:
  application/json:
    schema:
      type: array
      items:
        $ref: '#/components/schemas/VeryComplexType'

func (*Response) MarshalJSON added in v2.4.0

func (r *Response) MarshalJSON() ([]byte, error)

type Schema

type Schema struct {
	Type                 string              `yaml:"type,omitempty"`
	Nullable             bool                `yaml:"-"`
	Title                string              `yaml:"title,omitempty"`
	Description          string              `yaml:"description,omitempty"`
	Ref                  string              `yaml:"$ref,omitempty"`
	Format               string              `yaml:"format,omitempty"`
	ContentEncoding      string              `yaml:"contentEncoding,omitempty"`
	Default              any                 `yaml:"default,omitempty"`
	Examples             []any               `yaml:"examples,omitempty"`
	Items                *Schema             `yaml:"items,omitempty"`
	AdditionalProperties any                 `yaml:"additionalProperties,omitempty"`
	Properties           map[string]*Schema  `yaml:"properties,omitempty"`
	Enum                 []any               `yaml:"enum,omitempty"`
	Minimum              *float64            `yaml:"minimum,omitempty"`
	ExclusiveMinimum     *float64            `yaml:"exclusiveMinimum,omitempty"`
	Maximum              *float64            `yaml:"maximum,omitempty"`
	ExclusiveMaximum     *float64            `yaml:"exclusiveMaximum,omitempty"`
	MultipleOf           *float64            `yaml:"multipleOf,omitempty"`
	MinLength            *int                `yaml:"minLength,omitempty"`
	MaxLength            *int                `yaml:"maxLength,omitempty"`
	Pattern              string              `yaml:"pattern,omitempty"`
	PatternDescription   string              `yaml:"patternDescription,omitempty"`
	MinItems             *int                `yaml:"minItems,omitempty"`
	MaxItems             *int                `yaml:"maxItems,omitempty"`
	UniqueItems          bool                `yaml:"uniqueItems,omitempty"`
	Required             []string            `yaml:"required,omitempty"`
	MinProperties        *int                `yaml:"minProperties,omitempty"`
	MaxProperties        *int                `yaml:"maxProperties,omitempty"`
	ReadOnly             bool                `yaml:"readOnly,omitempty"`
	WriteOnly            bool                `yaml:"writeOnly,omitempty"`
	Deprecated           bool                `yaml:"deprecated,omitempty"`
	Extensions           map[string]any      `yaml:",inline"`
	DependentRequired    map[string][]string `yaml:"dependentRequired,omitempty"`

	OneOf []*Schema `yaml:"oneOf,omitempty"`
	AnyOf []*Schema `yaml:"anyOf,omitempty"`
	AllOf []*Schema `yaml:"allOf,omitempty"`
	Not   *Schema   `yaml:"not,omitempty"`

	// OpenAPI specific fields
	Discriminator *Discriminator `yaml:"discriminator,omitempty"`
	// contains filtered or unexported fields
}

Schema represents a JSON Schema compatible with OpenAPI 3.1. It is extensible with your own custom properties. It supports a subset of the full JSON Schema spec, designed specifically for use with Go structs and to enable fast zero or near-zero allocation happy-path validation for incoming requests.

Typically you will use a registry and `huma.SchemaFromType` to generate schemas for your types. You can then use `huma.Validate` to validate incoming requests.

// Create a registry and register a type.
registry := huma.NewMapRegistry("#/prefix", huma.DefaultSchemaNamer)
schema := huma.SchemaFromType(registry, reflect.TypeOf(MyType{}))

Note that the registry may create references for your types.

func SchemaFromField

func SchemaFromField(registry Registry, f reflect.StructField, hint string) *Schema

SchemaFromField generates a schema for a given struct field. If the field is a struct (or slice/map of structs) then the registry is used to potentially get a reference to that type.

This is used by `huma.SchemaFromType` when it encounters a struct, and is used to generate schemas for path/query/header parameters.

func SchemaFromType

func SchemaFromType(r Registry, t reflect.Type) *Schema

SchemaFromType returns a schema for a given type, using the registry to possibly create references for nested structs. The schema that is returned can then be passed to `huma.Validate` to efficiently validate incoming requests.

// Create a registry and register a type.
registry := huma.NewMapRegistry("#/prefix", huma.DefaultSchemaNamer)
schema := huma.SchemaFromType(registry, reflect.TypeOf(MyType{}))

func (*Schema) MarshalJSON

func (s *Schema) MarshalJSON() ([]byte, error)

MarshalJSON marshals the schema into JSON, respecting the `Extensions` map to marshal extensions inline.

func (*Schema) PrecomputeMessages

func (s *Schema) PrecomputeMessages()

PrecomputeMessages tries to precompute as many validation error messages as possible so that new strings aren't allocated during request validation.

type SchemaLinkTransformer

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

SchemaLinkTransformer is a transform that adds a `$schema` field to the response (if it is a struct) and a Link header pointing to the JSON Schema that describes the response structure. This is useful for clients to understand the structure of the response and enables things like as-you-type validation & completion of HTTP resources in editors like VSCode.

func NewSchemaLinkTransformer

func NewSchemaLinkTransformer(prefix, schemasPath string) *SchemaLinkTransformer

NewSchemaLinkTransformer creates a new transformer that will add a `$schema` field to the response (if it is a struct) and a Link header pointing to the JSON Schema that describes the response structure. This is useful for clients to understand the structure of the response and enables things like as-you-type validation & completion of HTTP resources in editors like VSCode.

func (*SchemaLinkTransformer) OnAddOperation

func (t *SchemaLinkTransformer) OnAddOperation(oapi *OpenAPI, op *Operation)

OnAddOperation is triggered whenever a new operation is added to the API, enabling this transformer to precompute & cache information about the response and schema.

func (*SchemaLinkTransformer) Transform

func (t *SchemaLinkTransformer) Transform(ctx Context, status string, v any) (any, error)

Transform is called for every response to add the `$schema` field and/or the Link header pointing to the JSON Schema.

type SchemaProvider

type SchemaProvider interface {
	Schema(r Registry) *Schema
}

SchemaProvider is an interface that can be implemented by types to provide a custom schema for themselves, overriding the built-in schema generation. This can be used by custom types with their own special serialization rules.

type SchemaTransformer added in v2.18.0

type SchemaTransformer interface {
	TransformSchema(r Registry, s *Schema) *Schema
}

SchemaTransformer is an interface that can be implemented by types to transform the generated schema as needed. This can be used to leverage the default schema generation for a type, and arbitrarily modify parts of it.

type SecurityScheme

type SecurityScheme struct {
	// Type is REQUIRED. The type of the security scheme. Valid values are
	// "apiKey", "http", "mutualTLS", "oauth2", "openIdConnect".
	Type string `yaml:"type"`

	// Description for security scheme. CommonMark syntax MAY be used for rich
	// text representation.
	Description string `yaml:"description,omitempty"`

	// Name is REQUIRED. The name of the header, query or cookie parameter to be
	// used.
	Name string `yaml:"name,omitempty"`

	// In is REQUIRED. The location of the API key. Valid values are "query",
	// "header" or "cookie".
	In string `yaml:"in,omitempty"`

	// Scheme is REQUIRED. The name of the HTTP Authorization scheme to be used in
	// the Authorization header as defined in [RFC7235]. The values used SHOULD be
	// registered in the IANA Authentication Scheme registry.
	Scheme string `yaml:"scheme,omitempty"`

	// BearerFormat is a hint to the client to identify how the bearer token is
	// formatted. Bearer tokens are usually generated by an authorization server,
	// so this information is primarily for documentation purposes.
	BearerFormat string `yaml:"bearerFormat,omitempty"`

	// Flows is REQUIRED. An object containing configuration information for the
	// flow types supported.
	Flows *OAuthFlows `yaml:"flows,omitempty"`

	// OpenIDConnectURL is REQUIRED. OpenId Connect URL to discover OAuth2
	// configuration values. This MUST be in the form of a URL. The OpenID Connect
	// standard requires the use of TLS.
	OpenIDConnectURL string `yaml:"openIdConnectUrl,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

SecurityScheme defines a security scheme that can be used by the operations.

Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), mutual TLS (use of a client certificate), OAuth2’s common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749], and OpenID Connect Discovery. Please note that as of 2020, the implicit flow is about to be deprecated by OAuth 2.0 Security Best Current Practice. Recommended for most use case is Authorization Code Grant flow with PKCE.

type: http
scheme: bearer
bearerFormat: JWT

func (*SecurityScheme) MarshalJSON added in v2.4.0

func (s *SecurityScheme) MarshalJSON() ([]byte, error)

type Server

type Server struct {
	// URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in {brackets}.
	URL string `yaml:"url"`

	// Description of the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Variables map between a variable name and its value. The value is used for substitution in the server’s URL template.
	Variables map[string]*ServerVariable `yaml:"variables,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Server URL, optionally with variables.

servers:
- url: https://development.gigantic-server.com/v1
  description: Development server
- url: https://staging.gigantic-server.com/v1
  description: Staging server
- url: https://api.gigantic-server.com/v1
  description: Production server

func (*Server) MarshalJSON added in v2.4.0

func (s *Server) MarshalJSON() ([]byte, error)

type ServerVariable

type ServerVariable struct {
	// Enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty.
	Enum []string `yaml:"enum,omitempty"`

	// Default value to use for substitution, which SHALL be sent if an alternate value is not supplied.
	Default string `yaml:"default"`

	// Description for the server variable. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

ServerVariable for server URL template substitution.

func (*ServerVariable) MarshalJSON added in v2.4.0

func (v *ServerVariable) MarshalJSON() ([]byte, error)

type StatusError

type StatusError interface {
	GetStatus() int
	Error() string
}

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 StreamResponse

type StreamResponse struct {
	Body func(ctx Context)
}

StreamResponse is a response that streams data to the client. The body function will be called once the response headers have been written and the body writer is ready to be written to.

func handler(ctx context.Context, input *struct{}) (*huma.StreamResponse, error) {
	return &huma.StreamResponse{
		Body: func(ctx huma.Context) {
			ctx.SetHeader("Content-Type", "text/my-type")

			// Write some data to the stream.
			writer := ctx.BodyWriter()
			writer.Write([]byte("Hello "))

			// Flush the stream to the client.
			if f, ok := writer.(http.Flusher); ok {
				f.Flush()
			}

			// Write some more...
			writer.Write([]byte("world!"))
		}
	}
}

type Tag

type Tag struct {
	// Name is REQUIRED. The name of the tag.
	Name string `yaml:"name"`

	// Description for the tag. CommonMark syntax MAY be used for rich text
	// representation.
	Description string `yaml:"description,omitempty"`

	// ExternalDocs is additional external documentation for this tag.
	ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

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

func (*Tag) MarshalJSON added in v2.4.0

func (t *Tag) MarshalJSON() ([]byte, error)

type Transformer

type Transformer func(ctx Context, status string, v any) (any, error)

Transformer is a function that can modify a response body before it is serialized. The `status` is the HTTP status code for the response and `v` is the value to be serialized. The return value is the new value to be serialized or an error.

type ValidateMode

type ValidateMode int

ValidateMode describes the direction of validation (server -> client or client -> server). It impacts things like how read-only or write-only fields are handled.

const (
	// ModeReadFromServer is a read mode (response output) that may ignore or
	// reject write-only fields that are non-zero, as these write-only fields
	// are meant to be sent by the client.
	ModeReadFromServer ValidateMode = iota

	// ModeWriteToServer is a write mode (request input) that may ignore or
	// reject read-only fields that are non-zero, as these are owned by the
	// server and the client should not try to modify them.
	ModeWriteToServer
)

type ValidateResult

type ValidateResult struct {
	Errors []error
}

ValidateResult tracks validation errors. It is safe to use for multiple validations as long as `Reset()` is called between uses.

func (*ValidateResult) Add

func (r *ValidateResult) Add(path *PathBuffer, v any, msg string)

Add an error to the validation result at the given path and with the given value.

func (*ValidateResult) Addf

func (r *ValidateResult) Addf(path *PathBuffer, v any, format string, args ...any)

Addf adds an error to the validation result at the given path and with the given value, allowing for fmt.Printf-style formatting.

func (*ValidateResult) Reset

func (r *ValidateResult) Reset()

Reset the validation error so it can be used again.

Directories

Path Synopsis
adapters
humaflow/flow
Package flow is a delightfully simple, readable, and tiny HTTP router for Go web applications.
Package flow is a delightfully simple, readable, and tiny HTTP router for Go web applications.
Package autopatch provides a way to automatically generate PATCH operations for resources which have a GET & PUT but no PATCH.
Package autopatch provides a way to automatically generate PATCH operations for resources which have a GET & PUT but no PATCH.
Package casing helps convert between CamelCase, snake_case, and others.
Package casing helps convert between CamelCase, snake_case, and others.
Package conditional provides utilities for working with HTTP conditional requests using the `If-Match`, `If-None-Match`, `If-Modified-Since`, and `If-Unmodified-Since` headers along with ETags and last modified times.
Package conditional provides utilities for working with HTTP conditional requests using the `If-Match`, `If-None-Match`, `If-Modified-Since`, and `If-Unmodified-Since` headers along with ETags and last modified times.
docs
formats
cbor
Package cbor provides a CBOR formatter for Huma with default configuration.
Package cbor provides a CBOR formatter for Huma with default configuration.
Package humatest provides testing utilities for Huma services.
Package humatest provides testing utilities for Huma services.
Package negotiation provides utilities for working with HTTP client- driven content negotiation.
Package negotiation provides utilities for working with HTTP client- driven content negotiation.
Package queryparam provides utilities for efficiently working with query parameters in URLs.
Package queryparam provides utilities for efficiently working with query parameters in URLs.
Package sse provides utilities for working with Server Sent Events (SSE).
Package sse provides utilities for working with Server Sent Events (SSE).
Package yaml implements a converter from JSON to YAML.
Package yaml implements a converter from JSON to YAML.

Jump to

Keyboard shortcuts

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