itczl
itczl

Reputation: 113

Is there a function similar to PHP's isset() in Go?

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

Answers (2)

abhink
abhink

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

Randy
Randy

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

source

Upvotes: 1

Related Questions