【openresty】引用第三方resty库 --- resty.http

OpenResty 引用第三方 resty 库,只需要将该库的 lua 文件拷贝到 resty 目录下即可。

> cd /usr/local/openresty/lualib/resty/

> curl -o http_connect.lua https://raw.githubusercontent.com/ledgetech/lua-resty-http/master/lib/resty/http_connect.lua

> curl -o http_headers.lua https://raw.githubusercontent.com/ledgetech/lua-resty-http/master/lib/resty/http_headers.lua

> curl -o http.lua https://raw.githubusercontent.com/ledgetech/lua-resty-http/master/lib/resty/http.lua

代码示例:

修改default.conf文件,在server模块中增加如下

    location /httpbin {
        access_by_lua_block {
            local http = require "resty.http"
            local httpc = http.new()
            local res, err = httpc:request_uri("http://httpbin.org/get")
            if not res then
                ngx.say(err)
                return
            end
            ngx.say(res.body)
        }
    }

访问httpbin接口

❯ http http://127.0.0.1:8001/httpbin
HTTP/1.1 200 OK
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Date: Mon, 18 Oct 2021 08:56:42 GMT
Server: openresty/1.19.9.1
Transfer-Encoding: chunked

no resolver defined to resolve "httpbin.org"

返回报错无法解析域名“httpbin.org”, 因为缺少域名解析的配置。

增加一行:

    location /httpbin {
        resolver 8.8.8.8;

        access_by_lua_block {
            local http = require "resty.http"
            local httpc = http.new()
            local res, err = httpc:request_uri("http://httpbin.org/get")
            if not res then
                ngx.say(err)
                return
            end
            ngx.say(res.body)
        }
    }

再次请求可以看到接口成功返回。

❯ http http://127.0.0.1:8001/httpbin
HTTP/1.1 200 OK
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Date: Mon, 18 Oct 2021 09:00:07 GMT
Server: openresty/1.19.9.1
Transfer-Encoding: chunked

{
    "args": {},
    "headers": {
        "Host": "httpbin.org",
        "User-Agent": "lua-resty-http/0.16.1 (Lua) ngx_lua/10020",
        "X-Amzn-Trace-Id": "Root=1-616d3797-5df7ec746e559da113eedb34"
    },
    "origin": "159.138.88.145",
    "url": "http://httpbin.org/get"
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值