Skip to content

global agnostic middleware #257

@mybigman

Description

@mybigman

It appears that global middleware does not run without a route? If that is the case you can never terminate early.

Another scenario might be I have a middleware that looks for a specific header and does something with that before passing it down the chain regardless if the a route exists or not.

All other frameworks I have used handle this fine.

Its possible I have overlooked something in the docs?

func main() {
    api := humago.New(router, huma.DefaultConfig("My API", "1.0.0"))
    api.UseMiddleware(heartbeat.New("/ping"))
    addRoutes(api)
    ...
}
// heartbeat.go
func New(path string) func(ctx huma.Context, next func(huma.Context)) {
    return func(ctx huma.Context, next func(huma.Context)) {
        if (ctx.Method() == "GET" || ctx.Method() == "HEAD") && strings.EqualFold(ctx.URL().Path, path) {
            ctx.SetHeader("Content-Type", "text/plain")
            ctx.SetStatus(http.StatusOK)
            ctx.BodyWriter().Write([]byte("."))

            return
        }

        next(ctx)
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions