我正在尝试改进我的 Go 应用程序中处理登录的代码块。它接收一个login值和一个password值,然后检查该username字段或email数据库中的字段以查看是否可以找到用户。如果login包含@符号,则将使用电子邮件。所以我目前有:if strings.Contains(login, "@") { err := collection("users").Find(bson.M{"email" : login}).One(&user) if err != nil { //no user found api.WriteError(w, 400, "USER_NOT_FOUND", "No user found with email address: " + login) return }} else { err := collection("users").Find(bson.M{"username" : login}).One(&user) if err != nil { //no user found api.WriteError(w, 400, "USER_NOT_FOUND", "No user found with username: " + login) return }}//go on and check password但是您可以看到这不是很有效,因为我必须两次处理相同的错误。我也试过:if strings.Contains(login.Identifier, "@") { err := collection("users").Find(bson.M{}).One(&user)} else { err := collection("users").Find(bson.M{"username" : login}).One(&user)}if err != nil { //no user found api.WriteError(w, 400, "USER_NOT_FOUND", "No user found with email address: " + login) return}//go on and check password但err并不总是存在。我想过以某种方式使{"username" : login}零件成为字符串变量,但我似乎无法使其正常工作。
1 回答
弑天下
TA贡献1818条经验 获得超8个赞
像这样的东西?
field := "username"
if strings.Contains(login.Identifier, "@") {
field = "email"
}
err := collection("users").Find(bson.M{field: login}).One(&user)
if err != nil {
api.WriteError(w, 400, "USER_NOT_FOUND", "No user found with " + field + ": " + login)
}
- 1 回答
- 0 关注
- 192 浏览
添加回答
举报
0/150
提交
取消