Lua http套接字评估

问题描述

| 我使用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,header = mysocket.request(URL)) == nil then
    print(\'The server is unreachable on:\\n\'..URL)
    return
end
    

解决方法

是的,像这样:
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
请求将仅发送一次,如果失败,函数将退出。     ,更好的是,当请求失败时,第二个返回是原因:   如果失败,该函数将返回nil,然后返回错误消息。 (摘自http.request的文档) 因此,您可以直接从插槽的嘴中打印问题:
local http = require(\"socket.http\")
local response,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:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...