Files
resty_functions/scripts/lib/upyun_download.lua
T
2023-05-08 00:58:30 +08:00

60 lines
2.1 KiB
Lua

-- 指定模块引用目录,否则无法加载同目录下的其他文件
--package.path = package.path .. ';/usr/local/opt/openresty/nginx/scripts/?.lua';
local _M = {}
function _M.upyun_download(httpc, cjson, Upt, pl, uri)
ngx.log(ngx.INFO, "UPYUN DOWNLOAD : URI -> " .. uri)
local upt = Upt.upt(uri)
ngx.log(ngx.INFO, "UPYUN DOWNLOAD : UPT -> " .. upt)
local remote_url = ngx.var.upyun_domain .. uri .. "?_upt=" .. upt
ngx.log(ngx.INFO, "UPYUN DOWNLOAD : REMOTE_URL -> " .. remote_url)
-- ngx.log(ngx.INFO, "REQUEST UPYUN DOWNLOAD : HTTPC -> " .. pl.write(httpc))
local no_exception, resp, resp_err = pcall(httpc.request_uri, httpc, remote_url,
{
ssl_verify = false, -- 设置参数 ssl_verify 为false 不校验ssl证书
method = "GET",
})
ngx.log(ngx.INFO, "RESP -> ", pl.write(resp))
if no_exception == true then
if 200 ~= resp.status then
ngx.log(ngx.ERR, "UPYUN DOWNLOAD *FAILED*", pl.write(resp_err))
ngx.status = resp.status
-- ngx.say(pl.write(resp_err))
ngx.say(cjson.encode({r = false, d = nil, e = resp_err}))
ngx.exit(resp.status)
else
ngx.log(ngx.ERR, "RESP IS OK -> ", pl.write(resp.body))
-- return cjson.decode(resp.body).d
end
else
if resp == nil then
resp = ""
end
ngx.log(ngx.ERR, "FAILED TO CONNECT TO *UPYUN*: httpc throws runtime error, please check log. / ", pl.write(resp))
ngx.status = resp.status
ngx.say(cjson.encode({r = false, d = nil, e = resp.status}))
ngx.exit(resp.status)
end
-- TODO: send resp.body to Flask API (ai-api) -> convert_mxml_to_xml() -> XML string
-- local xml = ai-api.convert_mxml_to_xml(resp.body)
-- ngx.log(xml)
ngx.log(ngx.INFO, "RESP -> ", pl.write(resp))
-- save the content to a file
local f = assert(io.open('/tmp/test.jpg', 'wb')) -- open in "binary" mode
f:write(resp.body)
f:close()
ngx.say(cjson.encode({r = true, d = "/tmp/test.jpg", e = nil}))
ngx.exit(resp.status)
end
return _M