Reputation: 113
In an http request, I want to know if a request contains a specific parameter, similar to PHP's isset
function. How to test it in Go? Thanks.
Upvotes: 4
Views: 7241
Reputation: 9126
Once you have parsed the request, you can always check the parameter's value type to be equal to that type's zero value.
For example, you can use the "comma, ok" idiom to check query parameters:
u, err := url.Parse("http://google.com/search?q=term")
if err != nil {
log.Fatal(err)
}
q := u.Query()
if _, ok := q["q"]; ok {
// process q
}
Upvotes: 7
Reputation: 9819
The same issue was posted on Google Groups, this is the solution there:
func PrintUser(w http.ResponseWriter, r *http.Request) {
user := r.FormValue("user")
pass := r.FormValue("pass")
if user == "" || pass == "" {
fmt.Fprintf(w, "Missing username or password")
return
}
fmt.Fprintf(w, "Hi %s!", user) //I doubt you want to print the password.
}
Upvotes: 1