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.
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.
}
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
}