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

你可能感兴趣的:(Nginx)