location /test {
content_by_lua'
if ngx.var.cookies_user == nil then
ngx.say("cookies user:missing")
else
ngx.say("cookies user:[",ngx.var.cookies_user,"]")
end
';
}
利用curl命令行工具的--cookies name=value选项可以指定name=value为当前请求携带的cookie(通过添加相应的cookie请求头)。下面是若干次测试的结果:
$curl --cookie user=agentzh ‘http:/localhost:8080/test'
$curl --cookie user='http://localhost:8080/test'
$curl -- user= 'http://localhost:8080/test'
我们看到,cookieuser不存在以及取值为空字符串这两种情况被很好的分开了;当cookieuser不存在时候,lua代码中ngx.var.cookie_user返回了期望的luanil值。
在lua里访问未创建的nginx用户变量时,在lua里也会返回了期望的luanil值。
在lua里访问未创建nginx用户变量时,在lua里也会得到nil值,而不会像先前的例子那样直接让nginx拒绝加载配置:
location /test {
conten_by_lua'
ngx.say("$blah = ",ngx.var.blah)
';
}
这里假设我们并没有在当前的nginx.conf配置文件中创建用户变量$blah,然后我们在lua代码中通过ngx.var.blah直接引用它。上面这个配置可以顺利启动,因为nginx在加载配置时只会编译content_by_lua配置指令指定的lua 代码而不会实际执行它,所以nginx并不知道lua代码里引用了$blah这个变量。于是我们在运行时也会得到nil值。而ngx.lua提供的ngx.say函数会自动把lua的nul值格式化为字符串“nil”输出,于是访问/test接口的结果是:
curl 'http://location:8080/test'
$blah=nil
这个正是我们所期望的。