### Basic Hello World Example in Huma Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Initializes a Huma app with CLI, declares a resource operation, and defines its handler function. Use this for a complete basic setup. ```go 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() } ``` -------------------------------- ### Install Huma Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Install the Huma package using go get. Go 1.25 or newer is required. ```bash go get github.com/danielgtaylor/huma/v2 ``` -------------------------------- ### NewPathBuffer Initialization Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example of initializing a new PathBuffer and pushing an initial element. ```go pb := NewPathBuffer([]byte{}, 0) pb.Push("foo") ``` -------------------------------- ### Server Configuration Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example of how to define multiple servers with descriptions in a YAML configuration. ```yaml 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 ``` -------------------------------- ### OpenAPI Path Item Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example of a Path Item configuration for finding pets by ID, including GET operation details and parameters. ```yaml 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 ``` -------------------------------- ### Huma API Default Configuration Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Demonstrates creating and customizing API configuration using `huma.DefaultConfig`. This is a starting point for API setup, with default support for JSON, OpenAPI, docs, and schemas paths. ```go config := huma.DefaultConfig("My API", "1.0.0") router := chi.NewMux() api := humachi.New(router, config) ``` -------------------------------- ### Example License Configuration Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 An example configuration for the License object, specifying the license name and identifier. ```yaml name: Apache 2.0 identifier: Apache-2.0 ``` -------------------------------- ### PathBuffer With Usage Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example of using the With method to get the string representation of a path with an appended field. ```go pb.Push("foo") pb.With("bar") // returns foo.bar ``` -------------------------------- ### Example API Info Configuration Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 An example configuration for the Info object, demonstrating how to set API title, summary, description, terms of service, contact, license, and version. ```yaml 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 ``` -------------------------------- ### Example Structure for API Documentation Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 This YAML snippet illustrates the structure of an 'examples' object within an OpenAPI specification, used to provide concrete examples for request bodies. It shows how to define multiple examples with summaries and embedded values. ```yaml 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"} ``` -------------------------------- ### Response Example Configuration Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 An example configuration for a Response, specifying a JSON array content type with a schema reference. ```yaml description: A complex object array response content: application/json: schema: type: array items: $ref: '#/components/schemas/VeryComplexType' ``` -------------------------------- ### RequestBody Example Configuration Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 An example configuration for a RequestBody, specifying a JSON content type with a schema reference and an example user. ```yaml 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' ``` -------------------------------- ### ParamReactor OnParamSet Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example implementation of the OnParamSet method for the ParamReactor interface. ```go func (o *OptionalParam[T]) OnParamSet(isSet bool, parsed any) { o.IsSet = isSet } ``` -------------------------------- ### PathBuffer Push Usage Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Shows how to use the Push method to add simple string elements to the path. ```go pb.Push("foo") // foo pb.Push("bar") // foo.bar ``` -------------------------------- ### Example Struct Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 The Example struct is used to define examples for API request or response fields, including references, summaries, descriptions, and literal or external values. ```APIDOC ## Struct Example ### Description Example value of a request param or body or response header or body. ### Fields - **Ref** (string) - Reference to another example. Mutually exclusive with other fields. - **Summary** (string) - Short summary of the example. - **Description** (string) - Long description of the example, supporting CommonMark syntax. - **Value** (any) - Embedded literal example. Mutually exclusive with `ExternalValue`. - **ExternalValue** (string) - URI pointing to the literal example. Mutually exclusive with `Value`. - **Extensions** (map[string]any) - User-defined properties. ### Example Usage ```yaml 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"} ``` ``` -------------------------------- ### OAuthFlow Example Configuration Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example YAML configuration for OAuth2 flows, demonstrating implicit and authorizationCode flows with their respective URLs and scopes. ```yaml 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 ``` -------------------------------- ### PathBuffer Usage Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Demonstrates the usage of PathBuffer methods like Push, PushIndex, and Pop for constructing and manipulating path strings. ```go 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 ``` -------------------------------- ### ExternalDocs Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example of how to define external documentation for an API endpoint. ```yaml description: Find more info here url: https://example.com ``` -------------------------------- ### Example Header Schema Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 An example schema for a header parameter, specifying its description and schema type. ```yaml description: The number of allowed requests in the current period schema: type: integer ``` -------------------------------- ### Basic Flow Router Setup with Middleware and Routes Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humaflow/flow Demonstrates initializing a Flow router, applying top-level middleware, defining routes with multiple HTTP methods, using regular expressions for parameters, and implementing wildcard routes. This is useful for setting up the core routing logic of a Go web application. ```go package main import ( "fmt" "log" "net/http" "github.com/alexedwards/flow" ) func main() { mux := flow.New() // The Use() method can be used to register middleware. Middleware declared at // the top level will used on all routes (including error handlers and OPTIONS // responses). mux.Use(exampleMiddleware1) // Routes can use multiple HTTP methods. mux.HandleFunc("/profile/:name", exampleHandlerFunc1, "GET", "POST") // Optionally, regular expressions can be used to enforce a specific pattern // for a named parameter. mux.HandleFunc("/profile/:name/:age|^[0-9]{1,3}$", exampleHandlerFunc2, "GET") // The wildcard ... can be used to match the remainder of a request path. // Notice that HTTP methods are also optional (if not provided, all HTTP // methods will match the route). mux.Handle("/static/...", exampleHandler) // You can create route 'groups'. mux.Group(func(mux *flow.Mux) { // Middleware declared within in the group will only be used on the routes // in the group. mux.Use(exampleMiddleware2) mux.HandleFunc("/admin", exampleHandlerFunc3, "GET") // Groups can be nested. mux.Group(func(mux *flow.Mux) { mux.Use(exampleMiddleware3) mux.HandleFunc("/admin/passwords", exampleHandlerFunc4, "GET") }) }) err := http.ListenAndServe(":2323", mux) log.Fatal(err) } ``` -------------------------------- ### Create CLI with Options and Hooks Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/humacli Create a new CLI instance by defining your options struct and providing a callback function to `humacli.CLI`. This callback handles option parsing, server setup, and registers lifecycle hooks. ```go // First, define your input options. type Options struct { Debug bool `doc:"Enable debug logging"` Host string `doc:"Hostname to listen on."` Port int `doc:"Port to listen on." short:"p" default:"8888"` } // Then, create the CLI. cli := humacli.CLI(func(hooks humacli.Hooks, opts *Options) { fmt.Printf("Options are debug:%v host:%v port%v\n", opts.Debug, opts.Host, opts.Port) // Set up the router & API router := chi.NewRouter() api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0")) srv := &http.Server{ Addr: fmt.Sprintf("%s:%d", opts.Host, opts.Port), Handler: router, // TODO: Set up timeouts! } hooks.OnStart(func() { if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("listen: %s\n", err) } }) hooks.OnStop(func() { srv.Shutdown(context.Background()) }) }) // Run the thing! cli.Run() ``` -------------------------------- ### PathBuffer Pop Usage Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Demonstrates the effect of multiple Pop operations after pushing elements onto the path. ```go pb.Push("foo") // foo pb.PushIndex(1) // foo[1] pb.Push("bar") // foo[1].bar pb.Pop() // foo[1] pb.Pop() // foo ``` -------------------------------- ### PathBuffer PushIndex Usage Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Demonstrates using PushIndex to add an indexed element to the path. ```go pb.Push("foo") // foo pb.PushIndex(1) // foo[1] ``` -------------------------------- ### PathBuffer WithIndex Usage Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example of using the WithIndex method to get the string representation of a path with an appended index. ```go pb.Push("foo") pb.WithIndex(1) // return foo[1] ``` -------------------------------- ### OpenAPI Link Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Demonstrates how to define a link named 'address' within an OpenAPI response for a GET /users/{id} operation. This link references the 'getUserAddress' operation and passes the 'id' from the request path as the 'userId' parameter. ```yaml 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 ``` -------------------------------- ### MediaType Schema Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 An example of a MediaType object with a schema and an example for a 'cat'. This is used to define the structure and provide sample data for a media type. ```yaml 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 ``` -------------------------------- ### Creating and Populating an ErrorModel Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 This example demonstrates how to create an ErrorModel instance and populate its fields, including adding individual error details using the Errors slice. It shows how to set the title, status, detail, and specific error messages with locations and values. ```go 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, }, }, } ``` -------------------------------- ### SecurityScheme Example Configuration Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example configuration for an HTTP bearer token security scheme, specifying JWT as the bearer format. ```yaml type: http scheme: bearer bearerFormat: JWT ``` -------------------------------- ### Get Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/humatest Performs a GET request against the API using context.Background. Arguments can include headers or data structures to be serialized as JSON. ```APIDOC ## Get ### Description Performs a GET request against the API using `context.Background`. ### Method `Get(path string, args ...any)` ### Parameters #### Path Parameters - None explicitly defined, `path` is a string argument. #### Query Parameters - None explicitly defined. #### Request Body - `args ...any`: Can include string headers (e.g., `Content-Type: application/json`), an `io.Reader` for the request body, or a slice/map/struct which will be serialized to JSON. ### Request Example ```go // Example usage (assuming 'api' is an instance of TestAPI) // Make a GET request api.Get("/foo") // Make a GET request with a custom header. api.Get("/foo", "X-My-Header: my-value") ``` ### Response - Returns a `*httptest.ResponseRecorder`. ``` -------------------------------- ### Contact Information Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 An example of how to define contact information for an API, including name, URL, and email. This data is typically used in the OpenAPI specification. ```yaml name: API Support url: https://www.example.com/support email: support@example.com ``` -------------------------------- ### OpenAPI Components Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Illustrates the structure of the 'components' object in an OpenAPI specification, showcasing reusable schemas, parameters, responses, and security schemes. ```yaml 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 ``` -------------------------------- ### Create New Huma API with Echo Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humaecho Initializes a new Huma API instance using an existing Echo router. This is the standard way to start a Huma API with Echo. ```go func New(r *echo.Echo, config huma.Config) huma.API ``` -------------------------------- ### Implement a Streaming Response Handler Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example handler function that returns a `StreamResponse`. It sets a content type, writes data in chunks, and flushes the stream. ```go 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!")) } } } ``` -------------------------------- ### ParamWrapper Receiver Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Example implementation of the Receiver method for the ParamWrapper interface, returning the reflect.Value of a struct field. ```go func (o *OptionalParam[T]) Receiver() reflect.Value { return reflect.ValueOf(o).Elem().Field(0) } ``` -------------------------------- ### Testing the Huma API with curl Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Demonstrates how to make a request to the Huma API using curl after starting the server. This is useful for verifying API endpoints. ```bash # 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!" } ``` -------------------------------- ### Example Parameter Definition in YAML Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 This YAML snippet demonstrates how to define a required path parameter named 'username' for fetching a user. It includes its type, description, and schema. ```yaml name: username in: path description: username to fetch required: true schema: type: string ``` -------------------------------- ### Configure API with Default CBOR Format Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/formats/cbor Example of how to configure an API's huma.Config to use the DefaultCBORFormat for 'application/cbor' and 'cbor' content types. ```go config := huma.Config{} config.Formats = map[string]huma.Format{ "application/cbor": huma.DefaultCBORFormat, "cbor": huma.DefaultCBORFormat, } ``` -------------------------------- ### Create New Flow Mux Instance Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humaflow/flow Returns a new, initialized Mux instance. This is the starting point for configuring routes and middleware in the Flow router. ```go func New() *Mux { // ... implementation details ... } ``` -------------------------------- ### OpenAPI Request Body Encoding Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Demonstrates how to configure encoding for different properties within a multipart/form-data request body in an OpenAPI specification. ```yaml 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 ``` -------------------------------- ### Get Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Registers a GET HTTP operation handler for an API. The handler function should accept a context and a pointer to an input struct, returning a pointer to an output struct and an error. The input struct defines request parameters (path, query, header, cookie) and/or body, while the output struct defines response headers and body. ```APIDOC ## Get ### Description Registers a GET HTTP operation handler for an API. The handler function should accept a context and a pointer to an input struct, returning a pointer to an output struct and an error. The input struct defines request parameters (path, query, header, cookie) and/or body, while the output struct defines response headers and body. ### Function Signature ```go func Get[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), operationHandlers ...func(o *Operation)) ``` ### Example Usage ```go huma.Get(api, "/things", func(ctx context.Context, input *struct{ Body []Thing }) (*ListThingOutput, error) { // TODO: list things from DB... resp := &ListThingOutput{} resp.Body = []Thing{{ID: "1", Name: "Thing 1"}} return resp, nil }) ``` This is a convenience wrapper around `huma.Register`. ``` -------------------------------- ### Create Huma API with Fiber Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humafiber Use `New` to create a new Huma API instance integrated with a Fiber application. This is suitable for standard Fiber setups. ```go func New(r *fiber.App, config huma.Config) huma.API ``` -------------------------------- ### Create New API Instance Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Creates a new Huma API instance with the given configuration and router adapter. This function handles schema registry creation, default format setting, and OpenAPI/documentation route setup. ```go func NewAPI(config Config, a Adapter) API ``` ```go router := chi.NewMux() adapter := humachi.NewAdapter(router) config := huma.DefaultConfig("Example API", "1.0.0") api := huma.NewAPI(config, adapter) ``` -------------------------------- ### Create and Configure a Route Group Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Demonstrates creating a new route group with a prefix and applying middleware. Use this to group related routes and apply common settings like authentication. ```go grp := huma.NewGroup(api, "/v1") grp.UseMiddleware(authMiddleware) huma.Get(grp, "/users", func(ctx huma.Context, input *MyInput) (*MyOutput, error) { // Your code here... }) ``` -------------------------------- ### New Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humafiber Creates a new Huma API instance using the Fiber adapter. This function initializes the Huma API with a given Fiber application instance and configuration. ```APIDOC ## New ### Description Creates a new Huma API using the Fiber adapter. ### Signature ```go func New(r *fiber.App, config huma.Config) huma.API ``` ### Parameters * **r** (*fiber.App) - The Fiber application instance. * **config** (huma.Config) - The Huma API configuration. ### Returns * huma.API - The initialized Huma API instance. ``` -------------------------------- ### New Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humamux Creates a new Huma API instance for the given Gorilla mux router, configuration, and options. ```APIDOC ## func New ### Description Creates a new Huma API instance for the given Gorilla mux router, configuration, and options. ### Signature ```go func New(r *mux.Router, config huma.Config, options ...Option) huma.API ``` ### Parameters * **r** (*mux.Router) - The Gorilla mux router instance. * **config** (huma.Config) - The Huma configuration. * **options** (...Option) - Optional configuration options for the API. ### Returns * huma.API - The created Huma API instance. ``` -------------------------------- ### Enable CBOR Format Support Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Shows how to enable CBOR (binary format) support for the API by importing the CBOR package. This is an optional addition to the default configuration. ```go import _ "github.com/danielgtaylor/huma/v2/formats/cbor" ``` -------------------------------- ### Example Error Response Structure Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 An example JSON structure for an error response, detailing the schema, title, status, detail, and a list of specific errors with messages and locations. ```json { "$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 } ] } ``` -------------------------------- ### Register Get HTTP Operation Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Registers a GET HTTP operation handler for an API. The handler processes input from a request body and returns a response with headers and body. ```go func Get[I, O any](api API, path string, handler func(context.Context, *I) (*O, error), operationHandlers ...func(o *Operation)) ``` ```go huma.Get(api, "/things", func(ctx context.Context, input *struct{ Body []Thing }) (*ListThingOutput, error) { // TODO: list things from DB... resp := &ListThingOutput{} resp.Body = []Thing{{ID: "1", Name: "Thing 1"}} return resp, nil }) ``` -------------------------------- ### Get Function Signature Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/queryparam The Get function retrieves a query parameter by name without dynamic allocations. It is recommended for scenarios with few query parameters over using url.ParseQuery. It does not support multiple values for the same key. ```Go func Get(query, name string) string ``` -------------------------------- ### Get Route Parameter Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humaflow/flow Retrieves the value of a named parameter or wildcard from the request context. ```APIDOC ## Param ### Description Param is used to retrieve the value of a named parameter or wildcard from the request context. It returns the empty string if no matching parameter is found. ### Function Signature ```go func Param(ctx context.Context, param string) string ``` ### Parameters - **ctx** (context.Context) - The request context. - **param** (string) - The name of the parameter to retrieve. ``` -------------------------------- ### New Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humahttprouter Creates a new Huma API instance using an httprouter.Router. This function initializes the Huma API with the provided httprouter instance and configuration, enabling Huma's features on top of httprouter. ```APIDOC ## func New ### Description Creates a new Huma API instance using an httprouter.Router. ### Signature ```go func New(r *httprouter.Router, config huma.Config) huma.API ``` ### Parameters * **r** (*httprouter.Router) - The httprouter.Router instance to use. * **config** (huma.Config) - The Huma configuration to apply. ### Returns * (huma.API) - A new Huma API instance. ``` -------------------------------- ### New Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humaflow%40v2.38.0 Creates a new Huma API using an HTTP mux. This function initializes a Huma API instance with the provided multiplexer and configuration. ```APIDOC ## func New ### Description New creates a new Huma API using an HTTP mux. ### Signature ```go func New(m Mux, config huma.Config) huma.API ``` ### Example ```go mux := http.NewServeMux() api := humago.New(mux, huma.DefaultConfig("My API", "1.0.0")) ``` ``` -------------------------------- ### GetCtx Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/humatest Performs a GET request against the API with a custom context.Context. Arguments can include headers or data structures to be serialized as JSON. ```APIDOC ## GetCtx ### Description Performs a GET request against the API with a custom `context.Context`. ### Method `GetCtx(ctx context.Context, path string, args ...any)` ### Parameters #### Path Parameters - None explicitly defined, `path` is a string argument. #### Query Parameters - None explicitly defined. #### Request Body - `args ...any`: Can include string headers (e.g., `Content-Type: application/json`), an `io.Reader` for the request body, or a slice/map/struct which will be serialized to JSON. ### Request Example ```go // Example usage (assuming 'api' is an instance of TestAPI and 'ctx' is a context.Context) // Make a GET request api.GetCtx(ctx, "/foo") // Make a GET request with a custom header. api.GetCtx(ctx, "/foo", "X-My-Header: my-value") ``` ### Response - Returns a `*httptest.ResponseRecorder`. ``` -------------------------------- ### PathBuffer With Method Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Appends a string to the path, converts the result to a string, and then removes the appended string (short for push, string, pop). ```go func (b *PathBuffer) With(s string) string ``` -------------------------------- ### Create New Test Adapter Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/humatest Creates a new test adapter from a router. ```go func NewAdapter() huma.Adapter ``` -------------------------------- ### New Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humago Creates a new Huma API using an HTTP mux. This is the primary function for initializing an API instance. ```APIDOC ## func New ### Description New creates a new Huma API using an HTTP mux. ### Signature ```go func New(m Mux, config huma.Config) huma.API ``` ### Example ```go mux := http.NewServeMux() api := humago.New(mux, huma.DefaultConfig("My API", "1.0.0")) ``` ``` -------------------------------- ### Do Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/humatest Performs a request against the API using context.Background. Arguments can include headers, an io.Reader for the body, or data structures to be serialized as JSON. ```APIDOC ## Do ### Description Performs a request against the API using `context.Background`. ### Method `Do(method, path string, args ...any)` ### Parameters #### Path Parameters - None explicitly defined, `path` is a string argument. #### Query Parameters - None explicitly defined. #### Request Body - `args ...any`: Can include string headers (e.g., `Content-Type: application/json`), an `io.Reader` for the request body, or a slice/map/struct which will be serialized to JSON. ### Request Example ```go // Example usage (assuming 'api' is an instance of TestAPI) api.Do("GET", "/users") api.Do("POST", "/users", map[string]string{"name": "Jane Doe"}) ``` ### Response - Returns a `*httptest.ResponseRecorder`. ``` -------------------------------- ### New Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humachi Creates a new Huma API instance using the specified Chi router and configuration. It leverages the latest v5.x.x version of Chi. ```APIDOC ## func New ### Description New creates a new Huma API using the latest v5.x.x version of Chi. ### Signature ```go func New(r chi.Router, config huma.Config) huma.API ``` ``` -------------------------------- ### Create New Test API Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/humatest Creates a new router and test API. Optionally takes configuration to customize API creation. Defaults to JSON support if no configuration is provided. ```go func New(tb TB, configs ...huma.Config) (http.Handler, TestAPI) ``` -------------------------------- ### Fast Content Type Selection without Allocations (Go) Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/negotiation Employ `SelectQValueFast` for a high-performance, zero-allocation alternative to `SelectQValue` when determining the best content type from an allowed list based on an HTTP Accept header. ```go func SelectQValueFast(header string, allowed []string) string ``` -------------------------------- ### ModelValidator Validation Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Shows the output of the ModelValidator.Validate function when validation fails due to incorrect data types or values not meeting the specified constraints. ```go 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) } ``` -------------------------------- ### NewAdapter Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humamux Creates a new adapter for the given Gorilla mux router. ```APIDOC ## func NewAdapter ### Description Creates a new adapter for the given Gorilla mux router. ### Signature ```go func NewAdapter(r *mux.Router, options ...Option) huma.Adapter ``` ### Parameters * **r** (*mux.Router) - The Gorilla mux router instance. * **options** (...Option) - Optional configuration options for the adapter. ### Returns * huma.Adapter - The created Huma adapter instance. ``` -------------------------------- ### Create New Humachi Adapter Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humachi Create a new adapter for a given Chi router. ```go func NewAdapter(r chi.Router) huma.Adapter ``` -------------------------------- ### StatusError Interface Definition Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Defines the StatusError interface, which includes methods to get the HTTP status code and the error message. Used for errors with associated status codes. ```go type StatusError interface { GetStatus() int Error() string } ``` -------------------------------- ### ModelValidator Usage Example Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Demonstrates how to use ModelValidator to validate data against a Go struct with validation tags. This is useful for validating data outside the request/response flow, such as during application startup. ```go 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 := huma.NewModelValidator() errs := validator.Validate(reflect.TypeOf(MyExample{}), value) if errs != nil { fmt.Println("Validation error", errs) } ``` -------------------------------- ### AutoPatch Function Signature Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/autopatch The AutoPatch function automatically generates HTTP PATCH operations for resources that have GET and PUT methods but lack a PATCH operation. It can be called multiple times safely. ```go func AutoPatch(api huma.API) ``` -------------------------------- ### Select Best Content Type with Quality Values (Go) Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/negotiation Use `SelectQValue` to determine the best content type from an allowed list based on an HTTP Accept header. The first matching item is preferred in case of a tie. Returns an empty string if no match is found. ```go func SelectQValue(header string, allowed []string) string ``` -------------------------------- ### PathItem Operations Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Defines the operations available on a single path, including GET, PUT, POST, DELETE, OPTIONS, HEAD, PATCH, and TRACE. It also supports defining common parameters for all operations within the path. ```APIDOC ## GET /pets/{id} ### Description Returns pets based on ID. This operation is part of a path item that may have common parameters and descriptions. ### Method GET ### Endpoint /pets/{id} ### Parameters #### Path Parameters - **id** (array of string) - Required - ID of pet to use ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **items** (array of Pet) - Description of pet response - **error** (ErrorModel) - Description of error payload #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### NewAdapter Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humachi Initializes a new adapter for a given Chi router instance, enabling Huma's functionality within a Chi-based application. ```APIDOC ## func NewAdapter ### Description NewAdapter creates a new adapter for the given chi router. ### Signature ```go func NewAdapter(r chi.Router) huma.Adapter ``` ``` -------------------------------- ### Hooks Interface Definition Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/humacli The Hooks interface allows you to register callbacks for service startup and shutdown events. Use `OnStart` to begin server operations and `OnStop` for graceful termination. ```go type Hooks interface { // OnStart sets a function to call when the service should be started. This // is called by the default command if no command is given. The callback // should take whatever steps are necessary to start the server, such as // `httpServer.ListenAndServer(...)`. OnStart(func()) // OnStop sets a function to call when the service should be stopped. This // is called by the default command if no command is given. The callback // should take whatever steps are necessary to stop the server, such as // `httpServer.Shutdown(...)`. OnStop(func()) } ``` -------------------------------- ### PathBuffer Push Method Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 Adds a string entry to the path, automatically including a '.' separator if the path is not empty. ```go func (b *PathBuffer) Push(s string) ``` -------------------------------- ### Param Struct Definition Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2 The Param struct defines a single operation parameter. A unique parameter is defined by a combination of its name and location (in). It includes fields for name, location, description, required status, deprecation, schema, and examples. ```APIDOC ## Param Struct ### Description Defines a single operation parameter. A unique parameter is defined by a combination of a name and location. ### Fields - **Ref** (string) - `yaml:"$ref,omitempty"` - A reference to another example. Mutually exclusive with other fields. - **Name** (string) - `yaml:"name,omitempty"` - REQUIRED. The name of the parameter. Case-sensitive. Must correspond to a template expression in the path if `in` is "path". Ignored if `in` is "header" and name is "Accept", "Content-Type", or "Authorization". - **In** (string) - `yaml:"in,omitempty"` - REQUIRED. The location of the parameter. Possible values: "query", "header", "path", or "cookie". - **Description** (string) - `yaml:"description,omitempty"` - Description of the parameter, potentially including examples. CommonMark syntax is supported. - **Required** (bool) - `yaml:"required,omitempty"` - Determines if the parameter is mandatory. REQUIRED and true if `in` is "path". Defaults to false otherwise. - **Deprecated** (bool) - `yaml:"deprecated,omitempty"` - Specifies that a parameter is deprecated. Defaults to false. - **AllowEmptyValue** (bool) - `yaml:"allowEmptyValue,omitempty"` - Allows sending a parameter with an empty value. Only valid for query parameters. Defaults to false. Not recommended. - **Style** (string) - `yaml:"style,omitempty"` - Describes how the parameter value will be serialized. Defaults depend on the `in` value (e.g., "form" for query, "simple" for path). - **Explode** (*bool) - `yaml:"explode,omitempty"` - When true, makes parameter values of type array or object generate separate parameters. Default is true for "form" style, false for others. - **AllowReserved** (bool) - `yaml:"allowReserved,omitempty"` - Determines if the parameter value should allow reserved characters (RFC3986) without percent-encoding. Only applies to "query" parameters. Defaults to false. - **Schema** (*Schema) - `yaml:"schema,omitempty"` - Defines the type used for the parameter. - **Example** (any) - `yaml:"example,omitempty"` - An example of the parameter’s potential value. Mutually exclusive with `Examples`. - **Examples** (map[string]*Example) - `yaml:"examples,omitempty"` - Examples of the parameter’s potential value. Mutually exclusive with `Example`. - **Extensions** (map[string]any) - `yaml:",inline"` - User-defined properties. ### Example Usage ```yaml name: username in: path required: true schema: type: string ``` ``` -------------------------------- ### Create New Huma API with httprouter Source: https://pkg.go.dev/github.com/danielgtaylor/huma/v2/adapters/humahttprouter Initializes a new Huma API instance using an httprouter.Router and a huma.Config. This is the entry point for integrating Huma with httprouter. ```go func New(r *httprouter.Router, config huma.Config) huma.API ```