How to have an optional query in GET request using Gorilla Mux?
Asked Answered
K

2

11

I would like to have some of my query parameters be optional. As for now, I have

r.HandleFunc("/user", userByValueHandler).
    Queries(
        "username", "{username}",
        "email", "{email}",
    ).
    Methods("GET")

But in this case "username" AND "email" needs to be present in the request. I want to have more flexible choice: have 2 of them OR have just one of them (but not zero parameters).

Thanks!

Krys answered 12/4, 2017 at 21:28 Comment(0)
K
42

So I found the solution to re-write my logic as:

r.HandleFunc("/user", UserByValueHandler).Methods("GET")

And in UserByValueHandler we can have something like:

func UserByValueHandler(w http.ResponseWriter, r *http.Request) {
       v := r.URL.Query()

       username := v.Get("username")
       email := v.Get("email")
       .....
}
Krys answered 21/4, 2017 at 17:3 Comment(1)
I think that this is the best approach. When you register a Query with the gorilla mux function, what you are doing is assigning a handler for that specific route, with that specific query params. In my opinion, is better to have just one route and use different controllers/services depending on the presence of certain query. This way you can have the routes registered only one, and then decouple the api from the controller/service logic.Carriole
A
2

Just a comment to the previous answer.

We can just add two routes there, I feel it is more readable, like below:

r.HandleFunc("/user", userByValueHandler).
    Queries(
        "username", "{username}",
        "email", "{email}",
    ).
    Methods("GET")
r.HandleFunc("/user", UserByValueHandler).Methods("GET")
Agiotage answered 5/1, 2019 at 23:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.