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

☆樱花仙子☆ 提交于 2019-12-21 05:02:35

问题


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:


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:


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


来源:https://stackoverflow.com/questions/43379942/how-to-have-an-optional-query-in-get-request-using-gorilla-mux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!