openresty lua 發送http請求

openresty中http請求

環境構建:openresty docker
openresty實踐:openresty最佳實踐
依賴:lua-resty-http
可直接下載http.lua/http_headers.lua放到/usr/local/openresty/lualib/resty/目錄下即可

lua腳本對請求攔截

nginx.conf配置文件中如下處理
http模塊中添加

    # lua package path 支持引用/usr/local/lua/下目錄下的lua文件module引用
    lua_package_path "/usr/local/lua/?.lua;;";

server模塊中添加

        location /api {
            access_by_lua_file /usr/local/lua/user_access.lua;
            xxx
        }

http模塊工具類

http post請求使用application/x-www-form-urlencoded模式時,需要對body中的參數進行編碼後傳輸。但是lua對此支持不太好,所以需要自己主動編碼。

-- user_access.lua
local httpUtil = require("http_util")
-- url encode
local function urlEncode(s)
    s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end)
    return string.gsub(s, " ", "+")
end
-- url decode
local function urlDecode(s)  
    s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end)  
    return s  
end 
local url = "xxx"
local param = string.format("k=%s", urlEncode("xxx"))
httpUtil.httpPost(url, param)
-- http_util.lua
local http_util = {}

local http = require("resty.http")
local timeout = 60000

local function newClient()
    local httpC = http.new()
    httpC:set_timeout(timeout)
    return httpC
end

local contentType = "Content-Type"
local jsonEncode = "application/json; charset=utf-8"
local formEncode = "application/x-www-form-urlencoded"
local cJson = require("cjson")

-- httpGet
function http_util.httpGet(url)
    local httpc = newClient()
    local res, err = httpc:request_uri(url, {
        method = "GET",
        headers = {
            [contentType] = jsonEncode,
        }
    })
    if err or (not res) then
        ngx.log(ngx.ERR, "http get failed, err: ", err)
        return nil
    end
    ngx.log(ngx.INFO, "http get response body: ", res.body)
    if res.status == ngx.HTTP_OK then
        return cJson.decode(res.body)
    end
end

-- httpPost body需要進行編碼,如k=v k,v分別進行urlEncode
function http_util.httpPost(url, body)
    local httpc = newClient()
    local res, err = httpc:request_uri(url, {
        method = "POST",
        body = body,
        headers = {
            [contentType] = formEncode,
        }
    })
    ngx.log(ngx.INFO, "http post, body= ", body)
    if err or (not res) then
        ngx.log(ngx.ERR, "http post failed, err: ", err)
        return nil
    end
    ngx.log(ngx.INFO, "http post response body: ", res.body)
    if res.status == ngx.HTTP_OK then
        return cJson.decode(res.body)
    end
end

return http_util
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章