Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

gorilla

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!

like image 635
levo4ka Avatar asked Apr 12 '17 21:04

levo4ka


People also ask

How do I make query param optional?

By defining required attribute. In this case we specify that the particular query parameter is not required and we check whether it is null or not and do the rest.

Should query params be optional?

As query parameters are not a fixed part of a path, they can be optional and can have default values. In the example above they have default values of skip=0 and limit=10 .

Can we pass query param GET request?

To send query parameters in a GET request in JavaScript, we can pass a list of search query parameters using the URLSearchParams API.

Can post requests use query parameters?

Query parameters in POST requests For POST requests to UCWA 2.0, input can be specified in the request body or as one or more query parameters of the request. The following example shows a POST request on the note resource, with the input values in the request body.


2 Answers

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")
       .....
}
like image 69
levo4ka Avatar answered Oct 20 '22 12:10

levo4ka


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")
like image 2
Ron Avatar answered Oct 20 '22 12:10

Ron