訪問遠程數據相關函數
更新時間 2024-07-22 18:11:17
最近更新時間: 2024-07-22 18:11:17
分享文章
本文簡述訪問遠程數據相關函數的語法、作用、入參、返回值、示例。
ctyun.query_remote
函數信息詳見下表:
| 項目 | 描述 |
|---|---|
| 語法 | res, err = ctyun.query_remote(url, req_info, timeout?, direct2client?) |
| 作用 | 利用cosocket訪問第三方網站,得到響應內容。支持簡單的單次請求得到響應并處理、響應內容直接發送至客戶端兩種模式。 |
| 入參 | url:訪問第三方服務的url。示例:"//xy.daliqc.cn:80/session?type=1" req_info:請求信息,包括request_method,request body(POST時候需要),request headers,是否打開ssl認證。示例: { method = "POST", body = "hello world", headers = {}, ssl_verify = true } timeout: 超時時間,單位為毫秒。示例:30000,表示超時時間為30s。 direct2client: 是否直接發送至客戶端,布爾型。示例:true,標識直接發送至客戶端。注:開啟時請求第三方的request_method需要跟客戶端請求一致。 |
| 返回值 | res:響應結果,lua-table類型,{ status, headers, body }。當開啟direct2client時此項為字符串done。 err:錯誤信息。 |
示例:
簡單的單次請求
local res, err = ctyun.query_remote("//xy.daliqc.cn/session", {
method = "POST",
body = "a=1&b=2",
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
},
}, 30000)
if err then
return
end
-- At this point, the entire request / response is complete and the connection
-- will be closed or back on the connection pool.
local status = res.status
local length = res.headers["Content-Length"]
local body = res.body
響應直接發送客戶端
local res, err = ctyun.query_remote("//xy.daliqc.cn/session", {
method = "GET",
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
},
}, 30000, true)
if err then
return
end
ctyun.query_get_cache
函數信息詳見下表:
| 項目 | 描述 |
|---|---|
| 語法 | res, err = ctyun.query_get_cache(cache_host, cache_url, cache_mode, ttl, uri?, args?, timeouts?) |
| 作用 | 回源拉取文件并緩存,得到響應內容可編輯。如m3u8改寫,請求得到響應體,使用Lua腳本對響應體進行編輯后,重新計算Content-Length頭部,調用ngx.print() 響應客戶端經過處理后的響應。 |
| 入參 | cache_host: 緩存host。示例:daliqc.cn。 cache_url: 緩存url。示例:/static/origin.m3u8。 cache_mode: 固定緩存時間/跟隨源站緩存(定值 "fixed" / “follow”)。默認為fixed, 非合法輸入初始化為默認值。 ttl: 緩存時間,單位秒。如果是固定緩存,設置緩存多久; 如果跟隨源站也可以設置默認值(秒)。 uri:請求uri,缺省為當前的請求uri。示例:/static/origin.m3u8。 args:請求參數,缺省為當前的請求參數,支持lua-string和lua-table兩種格式。示例:a=1&b=2或者{a=1,b=2}。 timeouts:超時時間,array table格式。分別為connect_timeout、send_timeout、read_timout,單位ms。缺省為15000 60000 60000。示例:{15000, 15000, 15000}。 |
| 返回值 | res:響應結果,lua-table類型,{ status, headers, body }。 err:錯誤信息。 |
示例:
local res, err = ctyun.query_get_cache("daliqc.cn", "/static/origin.m3u8", "fixed", 86400, "/static/origin.m3u8", "a=1&b=2", {15000, 15000, 15000})
if err then
return
end
-- headers
for k, v in pairs(res.headers) do
ctyun.resp.set_header(k, v)
end
-- status
ctyun.resp.set_code(res.status)
local status = res.status
if status > 299 or status < 200 then
ctyun.resp.set_output(res.body)
end
-- process body
local body = res.body
if body then
-- 對響應的處理, process_body僅用于說明
-- body = process_body(body)
-- 重寫Content-Length響應頭,輸出響應
ctyun.resp.set_header("Content-Length", #body)
ctyun.resp.set_output(res.body)
end