英文:
|| 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论