dongzhuo3202 2017-12-18 20:29
浏览 57
已采纳

如果变量未定义,则返回复用器?

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.

  • 写回答

1条回答 默认 最新

  • dou91855 2017-12-18 21:03
    关注

    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
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?