当前位置: 首页 > 工具软件 > Ourls-Resty > 使用案例 >

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

东门修文
2023-12-01

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"
}

 类似资料: