一个场景是使用resty.http去请求上游HTTPS服务器,但上游服务器100次查询后强制关闭连接的,用haproxy代理来可以绕开这个限制,但如何在不用别的代理,直接用Lua来实现同样的功能
function _M.requset(self)
local httpc = self.httpc
local options = on(isEmpty(self.opts.options), {}, self.opts.options)
local ok, err = self:connect()
local method = string.upper(self.opts.method)
if not ok then
ngx.log(ngx.ERR, "failed to connect: ", err)
return 500, '{"err":"500","msg":"failed to connect..."}'
end
if self.opts.protocol == "https" then
httpc:ssl_handshake(nil, self.opts.host, false)
end
options["Connection"] = "Keep-Alive";
options["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:48.0) Gecko/20100101 Firefox/48.0"
if method == "POST" then
options["Content-Type"] = "application/x-www-form-urlencoded"
options["Content-Type"] = "application/json"
options["Content-Length"] = string.len(self.opts.data)
end
local resp, err = httpc:request {
method = method,
path = self.opts.path,
body = on(method == "POST", self.opts.data, ""),
headers = options,
version = 1.1
};
if not resp then
if err == "timeout" then
httpc:close()
end
return ngx.log(ngx.ERR, "failed to request: ", err)
end
local body, err = resp:read_body()
if not body then
return nil, err
end
self:close()
return resp.status, body
end