Skip to content

huma middleware is not executed before route resolution #933

@adfourjaw

Description

@adfourjaw

I have a simple middleware that takes the place of a healthz endpoint:

func Healthz() func(huma.Context, func(huma.Context)) {
	return func(ctx huma.Context, next func(huma.Context)) {
		if strings.Contains(ctx.URL().Path, "/healthz") {
			return
		}
		next(ctx)
	}
}

and here's a test for said middleware:

func TestHealthz(t *testing.T) {
	tests := []struct {
		name               string
		path               string
		wantCode           int
		wantChainContinued bool
	}{
		{"healthz", "/healthz", http.StatusOK, false},
		{"other", "/other", http.StatusNotFound, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			chainContinued := false

			_, api := humatest.New(t)

			api.UseMiddleware(middleware.Healthz())
			api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
				chainContinued = true
			})

			res := api.Get(tt.path)

			assert.Equal(t, tt.wantCode, res.Code)
			assert.Equal(t, tt.wantChainContinued, chainContinued)
		})
	}
}

the requests attempted in the above tests immediately bail out with a 404 without even touching the middleware, contrary to the documentation for api.UseMiddleware

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

I thought this may just be the case for the huma test adapter, but it's the same for the humachi adapter.

I can easily see the argument that this is intentional, in which case this documentation needs a small update.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions