ngx.say
是 OpenResty 中最常用的函数之一,它的作用是往客户端输出字符串,类似于 PHP 中的 echo
。
一、ngx.say 的基本用法
使用 ngx.say
输出一个字符串非常简单,只需要在代码中调用 ngx.say
函数并将需要输出的字符串作为其参数即可:
location /test {
content_by_lua_block {
ngx.say("Hello, world!")
}
}
上述代码中,当访问 /test
路径时,将会输出 "Hello, world!"
字符串。
二、ngx.say 的高级用法之变量替换
有时需要将变量替换到需要输出的字符串中,可以使用 ngx.say
的变量替换功能,如下示例:
location /test {
set $hello "world";
content_by_lua_block {
ngx.say("Hello, $hello!")
}
}
上述代码中,我们首先定义了一个 $hello
变量,然后在 ngx.say
中使用了该变量,访问 /test
路径时将会输出 "Hello, world!"
字符串。
三、ngx.say 的高级用法之多个参数输出
有时需要输出多个数据,可以使用 ngx.say
的多个参数输出功能,如下示例:
location /test {
content_by_lua_block {
ngx.say("Hello,", "world!")
}
}
上述代码中,我们在 ngx.say
中传递了两个参数,访问 /test
路径时将会输出 "Hello,world!"
字符串。
四、ngx.say 的高级用法之 HTML 实体化
有时需要在输出的字符串中包含 HTML 标签,为了防止这些标签被浏览器解析,需要进行 HTML 实体化处理,可以使用 ngx.escape_html
函数,如下示例:
location /test {
content_by_lua_block {
ngx.say(ngx.escape_html("<p>Hello, world!</p>"))
}
}
上述代码中,我们在 ngx.say
中传递了由 ngx.escape_html
处理的字符串,访问 /test
路径时将会输出 "<p>Hello, world!</p>"
字符串。
五、ngx.say 的高级用法之 JSON 输出
有时需要将数据以 JSON 格式输出,可以使用 ngx.say
的 JSON 输出功能,如下示例:
location /test {
content_by_lua_block {
local data = {
name = "John",
age = 30,
city = "New York"
}
local json_str = cjson.encode(data)
ngx.header.content_type = "application/json;charset=utf-8"
ngx.say(json_str)
}
}
上述代码中,我们首先定义了一个包含 name
、age
、city
三个属性的 Lua 表,然后通过 cjson.encode
将该表转换为 JSON 格式的字符串,并设置响应头为 application/json;charset=utf-8
,最后将 JSON 字符串输出。
六、总结
在 OpenResty 开发中,ngx.say
是一个非常重要的函数,可以用于输出数据、调试信息等。除了基本用法外,ngx.say
还有许多高级用法,如变量替换、多个参数输出、HTML 实体化、JSON 输出等,这些用法可以帮助我们更加灵活地使用 ngx.say
,同时也能提高代码的复用性和可读性。