openrestry 响应慢的请求_OpenResty常用HTTP请求API

获取请求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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值