HUMA is a great Go framework that enables you to expose generated OpenAPI spec in the best way possible. Unfortunately, it lacks some features from other routers.
This library wraps HUMA framework endpoints registration pipeline to provide the missing features:
Similar to other routers you can create a derived api
(i.e. group) that has pre-defined:
- Base path (same as
Group
,Route
methods in other routers) - Multiple alternative base paths
- Middlewares
- Transformers
- Tags and other Huma Operation properties that will be applied to all endpoints in a group.
- Control the registration pipeline preventing operation from registration or registering it multiple times with different properties
Now you have manual control over exposing the spec, docs and schemas:
- Expose only needed spec versions
- Add own middlewares (e.g. authentication to protect the spec on public APIs)
- Have separate scoped OpenAPI specs for different parts of your API
The library provides additional information via Metadata
field to your
own Operation Handlers:
- Input/Output types of a handler
- OpenAPI object from
huma.API
instance - Whether an operation was defined explicitly or implicitly via convenience methods
- etc.
go get github.com/cardinalby/hureg
- Operation metadata
- Per-group Transformers
- OpenAPI endpoints and multiple scoped specs
import "github.com/cardinalby/hureg"
httpServeMux := http.NewServeMux() // with go 1.22
cfg := huma.DefaultConfig("My API", "1.0.0") // default HUMA initialization
humaApi := humago.New(httpServeMux, cfg) // --
api := hureg.NewAPIGen(humaApi) // The new line
v1gr := api. // all operations registered with v1gr will have:
AddBasePath("/v1"). // - "/v1" base path
AddOpHandler(op_handler.AddTags("some_tag")). // - "some_tag" tag
AddMiddlewares(m1, m2) // - m1, m2 middlewares
hureg.Get(v1gr, "/cat", ...) // "/v1/cat" with "some_tag" tag and m1, m2 middlewares
hureg.Get(v1gr, "/dog", ...) // "/v1/dog" with "some_tag" tag and m1, m2 middlewares
Sometimes we need to register the same endpoint with multiple base paths (e.g. /v1
and /v2
).
multiPathGr := api.AddMultiBasePaths(nil, "/v1", "/v2")
hureg.Get(multiPathGr, "/sparrow", ...) // "/v1/sparrow"
// "/v2/sparrow"
trGr := api.AddTransformers(...) // transformers will be applied only to the operations
// registered in this group
hureg.Get(trGr, "/crocodile", ...)
Check out integration_test.go for a complete example of how to use the library:
- create
huma.API
fromhttp.ServeMux
router - create
APIGen
instance on top ofhuma.API
- register operations with
APIGen
instance- use base paths, tags and Transformers to the groups
- register OpenAPI endpoints manually with Basic Auth middleware
Uncommenting one line you can run the server and play with it in live mode.
Even though Huma declares Go 1.20 as the minimal supported version, it actually requires Go 1.22 for correct work
due to "slices" package usage. So hureg
requires Go 1.22 explicitly.