如何在使用Gorilla Mux时在GET请求中添加可选查询参数?

huangapple go评论80阅读模式
英文:

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")

huangapple
  • 本文由 发表于 2017年4月13日 05:28:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/43379942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定