我使用这里概述的 haproxy Socket 类https://www.haproxy.com/blog/5-ways-to-extend-haproxy-with-lua/#actions从 lua 代码向外部服务发出http请求(参见下面的代码)。
- 如何向服务发出https请求?
- 是否可以指定域名而不是要连接的服务的 IP 地址?
任何帮助表示赞赏。
local function http_request(txn, data)
local addr = <external-IP>
local port = 80
-- Set up a request to the service
local hdrs = {
[1] = string.format('host: %s:%s', addr, port),
[2] = 'accept: */*',
[3] = 'connection: close'
}
local req = {
[1] = string.format('GET %s HTTP/1.1', data.path),
[2] = table.concat(hdrs, '\r\n'),
[3] = '\r\n'
}
req = table.concat(req, '\r\n')
-- Use core.tcp to get an instance of the Socket class
local socket = core.tcp()
socket:settimeout(data.timeout)
-- Connect to the service and send the request
if socket:connect(addr, port) then
if socket:send(req) then
-- Skip response headers
while true do
local line, _ = socket:receive('*l')
if not line then break end
if line == '' then break end
end
-- Get response body, if any
local content = socket:receive('*a')
return content
else
core.Alert('Could not connect to server (send)')
end
socket:close()
else
core.Alert('Could not connect to server (connect)')
end
end