OpenResty 常用 HTTP 请求 API
OpenResty Lua 大约 1465 字获取请求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)
阅读 4566 · 发布于 2020-02-24
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Android MediaMetadataRetriever 获取多媒体文件信息阅读 3705
-
Java 中的 WebSocket阅读 1891
-
Java 并发编程之 AtomicInteger AtomicLong阅读 969
-
Elasticsearch 获取记录总数 _count阅读 10094
-
Spring Boot使用 Jackson 注解阅读 881
-
JavaScript 判断 Android 还是 iOS阅读 475
-
MySQL 行级锁演示阅读 577
-
Kubernetes 设置默认 namespace阅读 226
-
使用 MyBatis 注解接收 PostgreSQL 的 returning 结果阅读 3738
-
Linux ftp 操作阅读 1200