首页 > 解决方案 > socket http lua 设置超时

问题描述

我正在尝试创建一个可以使用 http 套接字 lua 调用 REST 的函数。我试图以这种方式设置超时。但是,当我运行这个函数时,超时没有运行。我应该如何设置超时?

local http = require "socket.http"
local socket = require "socket"
       
       local respbody = {} 
       http.request {
                     method = req_method,
                     url = req_url,
                     source = ltn12.source.string(req_body),
                     headers = 
                              {
                                ["Content-Type"] = req_content_type,
                                ["content-length"] = string.len(req_body),
                                ["Host"] = host,

                              },
            
                     sink = ltn12.sink.table(respbody),
                     create = function()
                         local req_sock = socket.tcp()
                         req_sock:settimeout(3, 't')
                         return req_sock
                     end,

}

标签: apirestluatimeout

解决方案


如果我按照我的要求实现这个例子,会是这样吗?cmiiw

local http_client = require "http.client" 
local req_body = "key1=value1&key2=value2" 
local myconnection = http_client.connect { 
    method = "POST"; 
    url = "myrestserver.domain.com/api/example"; 
    host = "myrestserver.domain.com"; 
    source = req_body 
    headers = { 
       ["Content-Type"] = "application/x-www-form-urlencoded", 
       ["content-length"] = string.len(req_body), 
    }, 
    timeout = 2; 
}

推荐阅读