【问题标题】:Openresty: Make an http call with lua and return its parsed resultOpenresty:使用 lua 进行 http 调用并返回其解析结果
【发布时间】:2018-02-19 10:48:53
【问题描述】:

我的问题

我正在使用 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 [错误] 7#7: *1 open() “/usr/local/openresty/nginx/htmlhttp://localhost:8080/functions.json” 失败(2:没有这样的文件或目录),客户端:172.17.0.1,服务器:, 请求:“GET / HTTP/1.1”,子请求: “http://localhost:8080/functions.json”,主机:“localhost:8080”

我的问题

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

【问题讨论】:

    标签: nginx lua openresty


    【解决方案1】:

    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;
        }
    }
    

    【讨论】:

    【解决方案2】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 1970-01-01
      • 2019-11-19
      • 2016-07-04
      • 2012-01-26
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多