UsamaAmjad
UsamaAmjad

Reputation: 4604

Gorilla Mux same endpoint multiple query params

So I know that Gorilla Mux doesn't support optional query params and people suggest to create different routes with query param which makes it more solid. But in my case it is not resolving the routes as expected.

If I call /service/{locale}?param1=1,2&param2=3,4 then it invokes a.listFirst while it should call the a.listSecond and the same issue with other combinations. But:

  1. If I keep only one route then the route works as expected. So I assume the routes itself are fine but there is some resolving issue when they are together?
  2. If I remove the first route (the one without query param) and swap the order of the rest then they both work fine. This means the order also matters?

I know I can use request.URL.Query() to get the query params but I am curious to know why this way of defining query params as route doesn't work as expected?

a.Router.
    Methods(http.MethodGet).
    Path("/service/{locale}").
    Handler(negroni.New(
        a.contentTypeJSON,
        negroni.HandlerFunc(a.listAll),
    ))

a.Router.
    Methods(http.MethodGet).
    Path("/service/{locale}").
    Queries("param1", "{param1:[0-9,]+}").
    Handler(negroni.New(
        a.contentTypeJSON,
        negroni.HandlerFunc(a.listFirst),
    ))

a.Router.
    Methods(http.MethodGet).
    Path("/service/{locale}").
    Queries("param2", "{param2:[0-9,]+}", "param1", "{param1:[0-9,]+}").
    Handler(negroni.New(
        a.contentTypeJSON,
        negroni.HandlerFunc(a.listSecond),
    ))

I have already looked at these but they dont answer the question link1 link2

UPDATE

Short answer: Order matters

Tip: Don't be a fool and use correct handler function

Upvotes: 0

Views: 3791

Answers (2)

Saiprasanna Sastry
Saiprasanna Sastry

Reputation: 88

I would suggest using grpc-go , grpc-gateway and play around with that, you need not define extra query params this way. everything that is defined in you message can be passed as query params

Upvotes: -1

SamuelTJackson
SamuelTJackson

Reputation: 1537

You have to change the order because the order matters. The first match gets selected

a.Router.
    Methods(http.MethodGet).
    Path("/service/{locale}").
    Queries("param2", "{param2:[0-9,]+}", "param1", "{param1:[0-9,]+}").
    Handler(negroni.New(
        a.contentTypeJSON,
        negroni.HandlerFunc(a.listSecond),
    ))

a.Router.
    Methods(http.MethodGet).
    Path("/service/{locale}").
    Queries("param1", "{param1:[0-9,]+}").
    Handler(negroni.New(
        a.contentTypeJSON,
        negroni.HandlerFunc(a.listFirst),
    ))

a.Router.
    Methods(http.MethodGet).
    Path("/service/{locale}").
    Handler(negroni.New(
        a.contentTypeJSON,
        negroni.HandlerFunc(a.listAll),
    ))

Upvotes: 1

Related Questions