【openresty】向lua代码中传递参数

时间:2023-03-09 00:24:31
【openresty】向lua代码中传递参数

  前面介绍FormInputNginxModule模块时,明白了openresty如何获取post提交的数据。

  然后,如果需要通过lua处理这些数据,需要把数据作为参数传递到lua中,lua获取了这些数据,又会将结果返回到nginx内,从而完成整个流程。


  首先,有post请求:

 var json = {
data: "Hello!"
};
$.post(
'save',
json,
function(callback){
alert(callback);
}
);

  然后是nginx的相关配置:

 user root;
worker_processes ; error_log logs/error.log;
pid logs/nginx.pid; events {
worker_connections ;
# multi_accept on;
} http {
include mime.types; access_log logs/access.log; server {
listen ;
server_name localhost; location / {
root /var/www/aceEditor;
index index.htm index.html;
} location /save {
set_form_input $data data;
  echo $data;
}
}
}

  在介绍FormInputNginxModule模块时,我们看到这个配置通过set_form_input方法获取了post提交的data数据,并成功的将结果返回给了前台。

  现在,需要处理post上来的data数据,所以我们将data作为一个参数,传递到lua代码中,通过lua代码来处理这些数据,并且需要将结果返回给nginx。

  这里,更改nginx.conf的26~29行的配置:

 location /save {
set_form_input $data data;
set_by_lua $re '
local s = "张!!!"
return ngx.arg[] .. s;
' $data;
echo $re;
}

  其中,set_by_lua方法:

  语法:set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]

  作用:将参数列表传递到lua内,并且将lua的返回值赋值给res变量。

  在这里,set_by_lua方法将data作为参数传递到了lua代码内,在lua内通过ngx.arg[n]获取了这个参数,经过处理后将结果返回给了nginx,然后该结果赋值给了变量re,nginx再将re返回给了前台。ngx.arg[n]内的n表示传递参数的顺序。

  看看效果:

  【openresty】向lua代码中传递参数

  我们看到,前台正确的获取了nginx传递来的通过lua处理的结果数据。


  如果需要将lua代码独立出来,则可以使用set_by_lua_file方法。

  于是有lua文件m.lua:

 local s = "张!asdsd!!"
return ngx.arg[] .. s;

  再将上面的配置更改为:

 location /save {
set_form_input $data data;
set_by_lua_file $re /var/www/aceEditor/m.lua $data;
echo $re;
}

  看看结果:

  【openresty】向lua代码中传递参数