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!
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.
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 .
To send query parameters in a GET request in JavaScript, we can pass a list of search query parameters using the URLSearchParams API.
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.
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")
.....
}
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With