OpenResty 中使用 lua-resty-http 完成 HTTP 请求

OpenResty Lua HTTP About 1,228 words

项目介绍

lua-resty-httpOpenResty版本HTTP客户端,基于cosocket实现。

开源地址:https://github.com/ledgetech/lua-resty-http

对比ngx.location.capture

OpenResty中提供的子请求可以模拟HTTP请求,但有诸多限制。不能再定时任务ngx.timer中使用也使得许多需求不能依靠这个方法来完成。

快速入门

安装依赖

luarocks install lua-resty-http

代码示例

GET请求

local http = require('resty.http')
local httpc = http.new()
local res, err = httpc:request_uri('http://localhost/hello', {
    keepalive_timeout = 2000 -- 毫秒
})

if not res or res.status then
    ngx.log(ngx.ERR, "request error#", err)
    return
end

ngx.log(ngx.ERR, "request status#", res.status)
ngx.say(res.body)

POST请求

local http = require "resty.http"
local httpc = http.new()
local res, err = httpc:request_uri("http://localhost/hello", {
  method = "POST",
  body = "a=1&b=2",
  headers = {
    ["Content-Type"] = "application/x-www-form-urlencoded",
  },
  keepalive_timeout = 60,
  keepalive_pool = 10
})

if not res or res.status then
    ngx.log(ngx.ERR, "request error#", err)
    return
end

ngx.log(ngx.ERR, "request status#", res.status)
ngx.say(res.body)

常用方法

httpc = http.new()

创建HTTP请求对象,失败返回nil和错误信息。

res, err = httpc:request_uri(uri, params)

发送请求,填入请求链接和参数。

httpc:set_timeout(time)

设置请求超时时间,单位:毫秒。

开源案例

https://github.com/fendoudebb/z-blog-openresty

Views: 14,495 · Posted: 2020-03-04

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh