resty.http

function httpgettransfer.transfer(source_key, target_key)
– ngx.log(ngx.INFO, “params:”, tostring(args))
– ngx.log(ngx.INFO, “headers:”, tostring(receive_headers))
– 引入http请求
local http = require “resty.http”
– 常用方法封装
local common = require(“azcommon.commonutils”)
– 当前请求的参数
local args = ngx.req.get_uri_args()
– 当前的headers
local receive_headers = ngx.req.get_headers()



--2、组合url请求Get请求 并获取参数 
--内网地址
local url = ngx.var.url


-- url = commonutils.concat_url(args, url)
-- ngx.log(ngx.INFO, "Current Url is :", url)
local httpc = http.new()
-- ms
-- https://github.com/ledgetech/lua-resty-http#set_timeouts
httpc:set_timeouts(8000, 8000, 8000)
local res, err = httpc:request_uri(url, {
method = "GET",
headers = receive_headers,
query = args
})
if err == nil then
-- 这里进行数据的重新封装
--local cjson = require "cjson"
--local currentData = cjson.decode(res.body);
--local returnData = {}
--returnData["mytotal"] = currentData["total"]
--returnData["mylist"] = currentData["list"]

--ngx.say(cjson.encode(returnData))
-- 替换操作 加上双引号和封号匹配度更高 缺点,会替换文本中的数据
local resStr = res.body
-- 遍历数组进行替换
for i = 1, #source_key do
-- ngx.log(ngx.INFO, "source value:", common.parse_json_key(source_key[i]))

resStr = string.gsub(resStr,common.parse_json_key(source_key[i]),common.parse_json_key(target_key[i]))
end

ngx.status = res.status
ngx.header["Content-Type"] = "application/json; charset=utf-8"
ngx.say(resStr)
else
ngx.log(ngx.ERR, "err:", err)
ngx.status = 500
ngx.say(err)
end
http:close() end <!-- more --> https://blog.csdn.net/qq_28929589/article/details/103375017


Category nginx