在 openresty nginx http 块中可以使用 lua 吗?

我想请求一些 api 并将响应设置为 nginx 变量。但它会说 "set_by_lua_block"指令在此不允许。如何实现这一点?

http {
  set_by_lua_block $hostIp {
    local http = require 'resty.http'
    local httpc = http.new()
    local res, err = httpc:request_uri('http://some-pai')
    local body, err = res:read_body()
    ngx.log(ngx.INFO, "Using ngx.INFO")
    ngx.log(ngx.INFO, body)
    return body
  }

  ...
}
点赞
用户2060502
用户2060502

set_by_lua_block 在http上下文中不被允许使用。

https://github.com/openresty/lua-nginx-module#set_by_lua

set_by_lua_* 可以在服务器上下文中使用。

但你的代码实际上不起作用,因为 resty.http使用了cosocket API。

目前在 set_by_lua 的上下文中,以下至少有这些 API 函数被禁用了:

输出的 API 函数 (例如 ngx.say 和 ngx.send_headers)

控制的 API 函数 (例如 ngx.exit)

子请求的 API 函数 (例如 ngx.location.capture 和 ngx.location.capture_multi)

Cosocket 的 API 函数 (例如 ngx.socket.tcp 和 ngx.req.socket).

睡眠的 API 函数 ngx.sleep.

如果你真的需要在 nginx 启动之前请求某些内容-编写脚本并设置环境变量。然后

set_by_lua $my_var 'return os.getenv("MY_VAR")';
2016-12-13 20:45:00