1

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That will do it. Thanks for the lightning fast answer.
1

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

1 Comment

@Heandel: No, httpCode will hold the socket error message. See citation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.