hbrls
hbrls

Reputation: 2150

Can I use lua in the openresty nginx http block

I want to request some api and set the response as a nginx variable. But it says "set_by_lua_block" directive is not allowed here. How can I achieve this?

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
  }

  ...
}

Upvotes: 1

Views: 5361

Answers (1)

Alexander Altshuler
Alexander Altshuler

Reputation: 3064

set_by_lua_block is not allowed in http context

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

set_by_lua_* may be used within server context.

But your code will not work anyway because resty.http uses cosocket API.

At least the following API functions are currently disabled within the context of set_by_lua:

Output API functions (e.g., ngx.say and ngx.send_headers)

Control API functions (e.g., ngx.exit)

Subrequest API functions (e.g., ngx.location.capture and ngx.location.capture_multi)

Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).

Sleeping API function ngx.sleep.

If you really need to request something once before nginx start - write script and set environment variable. Then

set_by_lua $my_var 'return os.getenv("MY_VAR")';

Upvotes: 1

Related Questions