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

时间:2017-09-11 08:46:30

标签: nginx lua 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;
    }
}

错误日志

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"

我的问题

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

2 个答案:

答案 0 :(得分:4)

Capture将允许您捕获内部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;
    }
}

答案 1 :(得分:2)

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

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