Connect to HTTPS upstream with lua-resty-http (LUA)
The lua-resty-http
is incredbily useful when you need some LUA in OpenResty to place external HTTP requests.
However, when you need it to do HTTPS things are just a little more complex - it's not a simple as passing it https
as a scheme, instead you need to make a specific call to trigger the SSL handshake
This snippet shows how to do that (using a keepalive pool to reduce connection overhead between requests)
Details
- Language: LUA
- License: BSD-3-Clause
Snippet
function fetch_via_https(server,path)
local httpc = http.new()
ok,err = httpc:connect(server,443)
then
ngx.log(ngx.ERR,"Connection Failed")
end
-- Trigger the SSL handshake
session, err = httpc:ssl_handshake(False, server, false)
local res, err = httpc:request {
path = path,
method = 'GET'
}
if not res then
ngx.log(ngx.ERR,"Request Failed")
httpc:close()
return False
end
-- Return the connection to the keepalive pool
httpc:set_keepalive()
-- Check the status, dispatcher will serve us a 302
if res.status == 200
then
body, err = res:read_body()
return body
end
return False
end
Usage Example
local res = fetch_via_https("www.example.invalid","/robots.txt")