Openresty: Make an http call with lua and return its parsed result

Adam Matan picture Adam Matan · Sep 11, 2017 · Viewed 11k times · Source

My problem

I am using openresty to build a simple server.

Upon calling this server, it should make another call to a different server, fetch a JSON result, process it and return the parsed result.

The server should be implemented in openresty for reasons beyond the scope if this question.


Code

error_log /dev/stdout info;

events {
    worker_connections  14096;
}

http {
    access_log off;
    lua_package_path ";;/usr/local/openresty/nginx/?.lua;";

    server {
        keepalive_requests 100000;
        proxy_http_version 1.1;
        keepalive_timeout 10;

        location / {
        content_by_lua_block {
                res = ngx.location.capture('http://localhost:8080/functions.json')
                ngx.say(res.body)
            }
        }

        location /functions {
            root /usr/local/openresty/nginx/html/;
        }

        listen 0.0.0.0:80 default_server;
    }
}

Error log

2017/09/11 08:27:49 [error] 7#7: *1 open() "/usr/local/openresty/nginx/htmlhttp://localhost:8080/functions.json" failed (2: No such file or directory), client: 172.17.0.1, server: , request: "GET / HTTP/1.1", subrequest: "http://localhost:8080/functions.json", host: "localhost:8080"

My question

How can I make an HTTP GET request from within a Lua content block in nginx openresty?

Answer

Tarun Lalwani picture Tarun Lalwani · Sep 11, 2017

Capture will allow you to capture internal nginx locations and not absolute urls

error_log /dev/stdout info;

events {
    worker_connections  14096;
}

http {
    access_log off;
    lua_package_path ";;/usr/local/openresty/nginx/?.lua;";

    server {
        keepalive_requests 100000;
        proxy_http_version 1.1;
        keepalive_timeout 10;

        location / {
        content_by_lua_block {
                res = ngx.location.capture('/functions.json')
                ngx.say(res.body)
            }
        }
        location /functions.json {
            proxy_pass http://localhost:8080/functions.json;
        }

        location /functions {
            root /usr/local/openresty/nginx/html/;
        }

        listen 0.0.0.0:80 default_server;
    }
}