danielgtaylor / danielgtaylor/huma

huma middleware is not executed before route resolution

Open
#933 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
4.4k
Forks
285
Avg merge
40m
Merged PRs (30d)
1

Description

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.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.