Search code examples
lualuasocket

Lua http socket evaluation


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)
    return
end

Solution

  • 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.