gogo-chi

Is it possible to differentiate a route on the same path but with a query?


I want to define methods on / and then on /?. So I did

r.Get("/", myHandlers.Get)
r.Get("/?id", myHandlers.GetById) 

But when I hit http://myurl/?id=xyz I never go to the GetById method. How can I differentiate them better in Go Chi?


Solution

  • The query parameters are not part of the route handling. So you only need one handler for the GET request to "/" and then differentiate if the id parameter is set or not.

    if id := r.URL.Query.Get("id"); id != "" {
        // call id function
    } else {
        // call normal get function
    }