Openresty:使用lua进行http调用并返回其解析结果

Ada*_*tan 4 lua nginx openresty

我的问题

我正在使用openresty构建一个简单的服务器。

调用此服务器后,它应再次调用另一台服务器,获取JSON结果,对其进行处理并返回解析后的结果。

如果出现此问题,则出于超出范围的原因,应在openresty中实施服务器。


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;
    }
}
Run Code Online (Sandbox Code Playgroud)

错误记录

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"

我的问题

如何在nginxopenresty 的Lua内容块中发出HTTP GET请求?

Tar*_*ani 5

捕获将允许您捕获内部Nginx位置,而不是绝对URL

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*tan 5

使用lua-resty-http包解决。将库复制到 nginx openresty 根目录,然后:

local http = require "resty.http"
local httpc = http.new()

local res, err = httpc:request_uri("http://127.0.0.1/functions.json", { method = "GET" })
// Use res.body to access the response
Run Code Online (Sandbox Code Playgroud)