|| 运算符不按预期工作

huangapple go评论68阅读模式
英文:

|| operator not working as expected

问题

这里出了什么问题?我百分之百确定我发送了一个HTTP POST请求,但不知何故,逻辑或运算符的工作方式不符合我的预期。在第一个示例中,服务器返回405错误,而在第二个示例中,代码继续执行。

不起作用的代码:

if req.Method != http.MethodPost || req.Method != http.MethodDelete {
	http.Error(res, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
	return
}

起作用的代码:

if req.Method != http.MethodPost {
	http.Error(res, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
	return
}
英文:

What is going wrong here? I am 100% sure I am sending a HTTP POST request, but somehow the OR operator is not working as I am expecting. In the first example the server returns a 405 and in the second example the code continues executing.

not working:

if req.Method != http.MethodPost || req.Method != http.MethodDelete {
	http.Error(res, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
	return
}

working:

if req.Method != http.MethodPost {
	http.Error(res, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
	return
}

答案1

得分: 2

"不是某事" 或者 "不是另一件互斥的事" 总是会成立,对吗?

如果它是 "method post",那么它就不会是 "delete",反之亦然,你可能想要使用 "&&"?

英文:

(Not something) OR (not something else mutually exclusive) is always going to be true isn't it?

If it is method post, it will not be delete and vice versa , you might want && ?

答案2

得分: 0

根据Kenny Grant的说法,你可能想要思考一下逻辑。也许这就是你的意思:

// 仅允许POST或DELETE请求
if req.Method != http.MethodPost && req.Method != http.MethodDelete {
http.Error(res, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}

英文:

Like Kenny Grant said, you might want to ponder about the logic. Perhaps this is what you meant:

// only allow POST or DELETE
if req.Method != http.MethodPost && req.Method != http.MethodDelete {
    http.Error(res, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
    return
}

huangapple
  • 本文由 发表于 2017年3月11日 03:50:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/42726635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定