Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker 诊断工具


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.saytemplate.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)
阅读 5660 · 发布于 2020-02-24

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批