【问题标题】:Mux return if variable not defined?如果未定义变量,则多路复用器返回?
【发布时间】:2017-12-18 20:29:41
【问题描述】:

我想处理未定义参数的情况。

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")
    }
}

我也试过if !params["ssid"] {

什么是正确的语法?


使用mux.Vars(r) 我正在尝试从以下位置捕获帖子参数:

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

ssid 是必需的,但 password 是可选的。

【问题讨论】:

  • 您使用的是什么框架/库? mux.Vars 返回什么?
  • @CeriseLimón 我用我要捕获的参数更新了问题。
  • @Howl 我正在使用github.com/gorilla/mux
  • @PhilipKirkbride 更新您的问题以包含您正在使用的库的名称(和链接);否则人们将不知道mux.Vars 是什么类型或一般如何提供帮助......
  • @maerics 好的,我认为mux 是一个非常受欢迎的库

标签: go mux


【解决方案1】:

使用以下命令检查是否存在多路复用请求变量:

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

此代码使用the two value index expression 来检查地图中是否存在密钥。

看起来您的意图是解析 JSON 请求正文,而不是访问多路复用器变量。在您的处理程序中执行此操作:

 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
 }

【讨论】:

  • 我认为如果我正确使用参数,这将是正确的(?)我不知道这是否正确,因为当我使用和不使用密码发布时,ok 中的代码运行但它只是打印空白。
猜你喜欢
  • 2016-11-04
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多