Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middleware not called when router has no routes #780

Closed
pd93 opened this issue Jan 9, 2023 · 3 comments
Closed

Middleware not called when router has no routes #780

pd93 opened this issue Jan 9, 2023 · 3 comments

Comments

@pd93
Copy link

pd93 commented Jan 9, 2023

When using a Chi router with no routes, global middlewares are not called. For example:

func main() {
	// Configure HTTP server
	r := chi.NewRouter()
	r.Use(
		middleware.Heartbeat("/ping"),
	)
	http.ListenAndServe(":3000", r)
}

Here, we have a router which uses the heartbeat middleware and no strongly defined routes. If I run this and call curl localhost:3000/ping, I get 404 page not found back.

If we then add an empty, unrelated handler to the router and call the same URL:

	r.Get("/foo", func(
		res http.ResponseWriter,
		req *http.Request,
	) {
		res.WriteHeader(http.StatusOK)
	})

I now get . back as expected instead.

I understand that this is an unusual scenario. Our particular use-case is that we have a set of services that use a combination of GRPC and HTTP. We want to be able to monitor all services in the same way, so a service that has only GRPC routes, still needs to have an HTTP endpoint that can be pinged. Our other services that are either HTTP-only, or a combination or HTTP/GRPC work fine, but GRPC-only ones currently don't.

@pkieltyka
Copy link
Member

pkieltyka commented Jan 9, 2023

hi there :) we're aware of this quirk. the best solution is to add a stub handler on "/" in your router. Chi mux requires at least one route to always be set.

@pd93
Copy link
Author

pd93 commented Jan 9, 2023

@pkieltyka Thanks for the quick response. I've added r.HandleFunc("/", r.NotFoundHandler()) and this works for now. Are there any plans to address this in the future or is this not possible? If not, feel free to close this. Thanks!

@pkieltyka
Copy link
Member

Sorry, no plans. It's a requirement to have a single route defined for any router.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants