Skip to content

proposal: change Middlewares to split per-request ctx #831

@costela

Description

@costela

Warning

This is (in its current form) a breaking proposal; so it should be targeted at v3.
Though there may be a way to introduce this without breakage.

The current middleware definition func(ctx huma.Context, next func(huma.Context)) receives the per-request ctx as well as the basically constant next parameter for each request. This makes it cumbersome to use middlewares that require "singleton" initialization (e.g. something using groupcache), because there's no way to access next on a per-registration basis.

I'd propose changing the definition of Middleware to:

type Middleware func(next func(Context)) func(Context)

This would allow stuff like:

huma.Register(api, huma.Operation{
	// ... 
	Middlewares: huma.Middlewares{
		func(next func(huma.Context)) func(huma.Context) {
			// initialize per-operation:
			m := func(ctx huma.Context) {
				// ...
			}
			return func(ctx huma.Context) {
				return m(ctx)
			}
		},
	},
}, someHandler)

WDYT?

Metadata

Metadata

Assignees

No one assigned

    Labels

    v3-ideasIdeas for a breaking version change

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions