我使用lua 5.1和luaSocket 2.0.2-4从Web服务器检索页面。我首先检查服务器是否正在响应,然后将Web服务器响应分配给lua变量。
local mysocket = require("socket.http")
if mysocket.request(URL) == nil then
print('The server is unreachable on:\n'..URL)
return
end
local response, httpCode, header = mysocket.request(URL)
一切都按预期工作,但请求执行两次。我想知道我是否可以做类似的事情(显然不起作用):
local mysocket = require("socket.http")
if (local response, httpCode, header = mysocket.request(URL)) == nil then
print('The server is unreachable on:\n'..URL)
return
end
答案 0 :(得分:5)
是的,就像这样:
local mysocket = require("socket.http")
local response, httpCode, header = mysocket.request(URL)
if response == nil then
print('The server is unreachable on:\n'..URL)
return
end
-- here you do your stuff that's supposed to happen when request worked
请求只会发送一次,如果失败,函数将退出。
答案 1 :(得分:1)
更好的是,当请求失败时,第二次返回是原因:
如果失败,该函数返回nil,后跟一条错误消息。
(来自the documentation for http.request)
所以你可以直接从插座口打印问题:
local http = require("socket.http")
local response, httpCode, header = http.request(URL)
if response == nil then
-- the httpCode variable contains the error message instead
print(httpCode)
return
end
-- here you do your stuff that's supposed to happen when request worked