I use lua 5.1 and the luaSocket 2.0.2-4 to retrieve a page from a web server. I first check if the server is responding and then assign the web server response to lua variables.
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)
Everything works as expected but the request is executed two times. I wonder if I could do Something like (which doesn't work obviously):
local mysocket = require("socket.http")
if (local response, httpCode, header = mysocket.request(URL)) == nil then
print('The server is unreachable on:\n'..URL)
开发者_Python百科 return
end
Yes, something like this :
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
Request will be sent only once, and function will exit if it failed.
Even better, when request fails, the second return is the reason:
In case of failure, the function returns nil followed by an error message.
(From the documentation for http.request)
So you can print the problem straight from the socket's mouth:
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
精彩评论