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.92k stars 1.85k forks source link

[BUG] API is probably broken for GetQueries per each method #744

Open amills-vibeirl opened 12 months ago

amills-vibeirl commented 12 months ago

Is there an existing issue for this?

Current Behavior

This API is inconsistent with the rest of the API:


if err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
    pathTemplate, err1 := route.GetPathTemplate()
    var queries, err2 = route.GetQueriesRegexp()

    if err1 == nil && err2 == nil {
        var methods, _ = route.GetMethods()

        for _, m := range methods {
            fmt.Println("ROUTE:", pathTemplate, route.GetName(), m, queries)
        }

    }
    return nil
}); err != nil {
    vibelog.Stdout.Error(err)
    os.Exit(1)
}

the problem is if we do this:


r.Methods("POST").Path("/v1/conversations").Queries("AAA","BBB").HandlerFunc(
  mw.Middleware(
    createNewChatConversation(c),
),
)

r.Methods("GET").Path("/v1/conversations").Queries("THIS IS NOT","THE SAME QUERIES").HandlerFunc(
  mw.Middleware(
      doSomethingElse(c),
  ),
)

for the same route, for different methods, there are DIFFERENT Queries attached, but with route.GetQueries, it is just returning one object when it should return different objects for different methods.

Right?

Expected Behavior

Different Queries returned for different methods for the same Path

Steps To Reproduce

No response

Anything else?

No response

GocaMaric commented 11 months ago

I understand your concern. The GetQueriesRegexp() method in the Gorilla Mux router returns the queries for a route, but it doesn’t differentiate between different methods (like GET, POST) for the same route. This is because the Gorilla Mux router treats each route as a separate entity, regardless of the HTTP method.

If you want to have different queries for different methods on the same route, you might need to handle this manually in your code. One way could be to store the queries for each method in a separate data structure and retrieve them based on the method.

Alternatively, you could consider registering the same path as different routes for different methods, each with its own set of queries. This way, GetQueriesRegexp() would return the correct set of queries for each method.

Here’s an example of how you might do this:

r.Methods("POST").Path("/v1/conversations").Queries("AAA","BBB").HandlerFunc(
  mw.Middleware(
    createNewChatConversation(c),
),
)

r.Methods("GET").Path("/v1/conversations").HandlerFunc(
  mw.Middleware(
      doSomethingElse(c),
  ),

)

In this example, the POST and GET methods for the “/v1/conversations” path are registered as separate routes, each with its own set of queries. This should allow GetQueriesRegexp() to return the correct set of queries for each method.