mux icon indicating copy to clipboard operation
mux copied to clipboard

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

Open 1Mark opened this issue 3 years ago • 2 comments

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 ?

1Mark avatar Dec 07 '22 15:12 1Mark

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

ah8ad3 avatar Jul 16 '23 14:07 ah8ad3

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.

theghostmac avatar Aug 04 '23 11:08 theghostmac