首页 > 解决方案 > 带有超时的 LUA curl 请求

问题描述

我使用 LUA 代码将 json-data 发送到后端:

local cURL = require("cURL")
local c, err = cURL.easy{
  url = "http://10.10.10.10",
  post = true,
  httpheader = { "Content-Type: application/json"; },
  postfields = jsonString
}

local ok, err = c:perform()

除了一件事,一切都完美无缺。如果我没有收到来自服务器的响应,我的脚本会继续工作。我需要添加一些超时,如果在超时期间我没有收到响应,请关闭连接。

标签: curllua

解决方案


根据官方文档 easy创建一个接收选项表作为参数的 Easy 对象:

 c = curl.easy{
   url = 'http://example.com',
   [curl.OPT_VERBOSE] = true,
 }

现在我认为您可以以同样的方式传递设置请求允许占用的最长时间的CURLOPT_TIMEOUT 参数。所以在代码中:

local c, err = cURL.easy{
  url = "http://10.10.10.10",
  post = true,
  httpheader = { "Content-Type: application/json"; },
  postfields = jsonString,
  [curl.OPT_TIMEOUT] = 60, --Your timeout of choice
}

同样,我之前不必实际使用此参数,但我相信它的工作方式与其他CURLOPT参数相同。


推荐阅读