获取nginx lua插件中的json数据

该代码示例展示了如何在NginxLua模块中使用resty.http库发送GET请求到指定API,接收返回的JSON数据,并使用cjson库解析JSON以获取username字段的值。如果请求失败或响应状态非200,代码会记录错误并返回500内部服务器错误。
摘要由CSDN通过智能技术生成

以下是一个使用ngx_lua模块的示例代码,用于获取nginx lua插件中http接口返回的json数据中的username值:

local http = require "resty.http"
local cjson = require "cjson.safe"

local httpc = http.new()
local res, err = httpc:request_uri("<http://example.com/api>", {
    method = "GET",
    headers = {
        ["Content-Type"] = "application/json",
    }
})

if not res then
    ngx.log(ngx.ERR, "failed to request: ", err)
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

if res.status ~= ngx.HTTP_OK then
    ngx.log(ngx.ERR, "request failed with status ", res.status)
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

local data = cjson.decode(res.body)
local username = data.username

ngx.say(username)

注意:这个示例代码假设http接口返回的json数据中确实包含了一个名为username的字段,如果不是这个字段,请将代码中的username改为实际的字段名称。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值