Search code examples
gomux

Mux return if variable not defined?


I want to handle the situation where a param wasn't defined.

import (
    // ...
    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/connect", Connect).Methods("POST")
    log.Fatal(http.ListenAndServe(":7777", router))
}



// ...

func Connect(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)

    if params["password"] == nil {
        fmt.Println("login without password")
    } else {
        fmt.Println("login with password")
    }
}

I also tried if !params["ssid"] {

What is the right syntax for this?


With mux.Vars(r) I'm trying to capture the post params from:

curl -H 'Content-Type: application/json' -d '{"ssid":"wifi"}' -X POST http://localhost:7777/connect

ssid is required but password is optional.


Solution

  • Use the following to check for presence of a mux request variable:

    params := mux.Vars(r)   
    password, ok := params["password"] 
    if ok {
       // password is set
    } else {
       // password is not set
    }
    

    This code uses the two value index expression to check for presence of the key in the map.

    It looks like your intent is to parse a JSON request body and not to access the mux variables. Do this in your handler:

     var m map[string]string
     err := json.NewDecoder(r.Body).Decode(&m)
     if err != nil {
         // handle error
     }
     password, ok := m["password"]
     if ok {
       // password is set
     } else {
       // password is not set
     }