通过 content_by_lua_file 参数我们可以为openresty nginx 的server中的http请求设置返回值,这样的操作可以使我们的nginx.conf看起来更简洁,代码逻辑机构更符合审美和写作逻辑。这就需要我从零开始认识lua!
输出随机字符串:
--[[
输出随机字符串
lua注释,单行采用--
--]]
--接收http请求参数
local args = ngx.req.get_uri_args()
--获取参数中的某个值,如果传入参数与lua参数不一致报400,参数错误。
local salt = args.salt
if not salt then
--ngx.HTTP_BAD_REQUEST为常量,指的是400。代码里尽量使用常量。
ngx.exit(ngx.HTTP_BAD_REQUEST)
end
--lua 字符串拼接使用 .. 完成
--用于获取时间戳,是带有缓存的。与Lua的日期库不同,不涉及系统调用。尽量使用Ngx给出的方法,以免发生性能问题。
local str = ngx.md5(ngx.time() .. salt)
ngx.say(str)
完成lua文件,我们需要在nginx.conf中添加请求,将代码添加到conf中的server中去:
location /get_random_string{
content_by_lua_file lua/get_random_string.lua;
}
因为conf文件中我们修改了lua_code_cache off;因此不必手动重启nginx,直接访问http://localhost:8080/get_random_string?salt=zykj即可,查看功能输出: