gorilla / mux

Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
https://gorilla.github.io
BSD 3-Clause "New" or "Revised" License
20.93k stars 1.85k forks source link

[question] How to retrieve the handler func without the middleware? #705

Open 1Mark opened 1 year ago

1Mark commented 1 year ago

I'm trying to write a test to confirm that both the POST and PATCH methods of the same URL go to the same handler. So I tried the following

var match mux.RouteMatch
var handler http.Handler
req := &http.Request{}
req.URL = &url.URL{Path: "/post"}
req.Method = "POST"
if builder.router.Match(req, &match) {
    handler = match.Handler
}
g.Expect(handler).ToNot(BeNil())
fmt.Println(handler)

handler func is actually the handler func but wrapped in the MDW. Therefore, I couldn't assert that the handler was equal to my desired handler func

Any tips ?

ah8ad3 commented 1 year ago

@1Mark It's been few months. Maybe this test from the repository will help you rewrite you're test if you still need any help.

theghostmac commented 1 year ago

Perhaps this?

var match mux.RouteMatch
var handler http.Handler
req := &http.Request{}
req.URL = &url.URL{Path: "/post"}
req.Method = "POST"

if builder.router.Match(req, &match) {
    // Get the matched handler along with middleware
    matchedHandler := match.MatchedHandler

    // Define a temporary http.HandlerFunc to capture the inner handler
    tempHandlerFunc := func(w http.ResponseWriter, r *http.Request) {
        handler = matchedHandler
    }

    // Call the middleware with the temporary handler
    for _, mw := range match.Handler.Middlewares() {
        tempHandlerFunc = mw(tempHandlerFunc)
    }

    // Now 'handler' should contain the inner handler without middleware
}

g.Expect(handler).ToNot(BeNil())
fmt.Println(handler)

Unrelated, but I'm looking to contribute to this project in any capacity, but all I'm seeing in Issues are questions and discussions.