Connect to HTTPS upstream with lua-resty-http



Published: 2020-09-16 10:57:31 +0000
Categories: LUA,

Language

LUA

Description

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)

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")

Requires

License

BSD-3-Clause

Keywords

lua-resty-http, https, openresty, lua,

Latest Posts


Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter