resty.http 是用于访问外部 Http 资源,外部 web 服务,RESTFul 等的轻量级 http 库。
一、安装 resty.http 库
git clone https://github.com/ledgetech/lua-resty-http.git
cd lua-resty-http/lib/resty
# 直接拷贝文件到 openresty 的 lualib
cp ./http_headers.lua /usr/local/openresty/lualib/resty/
cp ./http.lua /usr/local/openresty/lualib/resty/
二、简单使用
location /restyhttp {
resolver 8.8.8.8;
content_by_lua '
-- 引入 http 包
local http = require "resty.http"
local httpc = http:new()
local res, err = httpc:request_uri("http://baidu.com", {
method = "POST",
body = "a=1&b=2",
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
}
})
if not res then
ngx.say("fail to request ", err)
end
-- ngx.say(res.body) 直接输出响应体
-- ngx.say(res.status)
';
}