英文:
How to have an optional query in GET request using Gorilla Mux?
问题
我想让我的一些查询参数变成可选的。目前,我有以下代码:
r.HandleFunc("/user", userByValueHandler).
Queries(
"username", "{username}",
"email", "{email}",
).
Methods("GET")
但在这种情况下,请求中必须同时包含"username"和"email"参数。我希望有更灵活的选择:要么同时有这两个参数,要么只有其中一个(但不能没有参数)。
谢谢!
英文:
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!
答案1
得分: 41
所以我找到了重写逻辑的解决方案:
r.HandleFunc("/user", UserByValueHandler).Methods("GET")
在UserByValueHandler
中,我们可以有如下代码:
func UserByValueHandler(w http.ResponseWriter, r *http.Request) {
v := r.URL.Query()
username := v.Get("username")
email := v.Get("email")
.....
}
英文:
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")
.....
}
答案2
得分: 2
对于之前的回答,我有一个评论。
我们可以在那里添加两个路由,我觉得这样更易读,像下面这样:
r.HandleFunc("/user", userByValueHandler).
Queries(
"username", "{username}",
"email", "{email}",
).
Methods("GET")
r.HandleFunc("/user", UserByValueHandler).Methods("GET")
英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论