OpenResty 常用 HTTP 请求 API
OpenResty Lua About 1,465 words获取请求URL
ngx.var.request_uri
获取请求方法
ngx.req.get_method()
过滤非GET请求
if 'GET' ~= ngx.req.get_method() then
ngx.exit(ngx.HTTP_NOT_FOUND)
end
获取请求参数
获取GET请求参数
ngx.req.get_uri_args
:返回一个table
对象。
local args, err = ngx.req.get_uri_args()
if err == "truncated" then
-- one can choose to ignore or reject the current request here
end
for key, val in pairs(args) do
if type(val) == "table" then
ngx.say(key, ": ", table.concat(val, ", "))
else
ngx.say(key, ": ", val)
end
end
获取POST请求体
application/json
(也能接收form
表单)
ngx.req.read_body()
local data = ngx.req.get_body_data()
if data then
ngx.say("body data:")
ngx.print(data)
return
end
application/x-www-form-urlencoded
(也能接收json
)
ngx.req.read_body()
local args, err = ngx.req.get_post_args()
if err == "truncated" then
-- one can choose to ignore or reject the current request here
end
if not args then
ngx.say("failed to get post args: ", err)
return
end
for key, val in pairs(args) do
if type(val) == "table" then
ngx.say(key, ": ", table.concat(val, ", "))
else
ngx.say(key, "xxxxxxx ", val)
end
end
更改HTTP状态码
赋值ngx.status
(必须在ngx.say
或template.render
等内容输出前修改),不加ngx.exit
亦可。
ngx.status = ngx.HTTP_OK
ngx.say("aaa")
ngx.exit(ngx.HTTP_OK)
获取请求开始时间
ngx.req.start_time()
计算请求耗时
local request_time = ngx.now() - ngx.req.start_time()
耗时保留小数位
保留两位:%.2f
。
local request_time = ngx.now() - ngx.req.start_time()
string.format("%.2f", request_time)
Views: 6,267 · Posted: 2020-02-24
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...