OpenResty 如何引用第三方 resty 庫

2021-08-13 10:09 更新

OpenResty 引用第三方 resty 庫非常簡(jiǎn)單,只需要將相應(yīng)的文件拷貝到 resty 目錄下即可。

我們以 resty.http ( pintsized/lua-resty-http) 庫為例。

只要將 ?lua-resty-http/lib/resty/? 目錄下的 ?http.lua? 和 ?http_headers.lua? 兩個(gè)文件拷貝到 ?/usr/local/openresty/lualib/resty? 目錄下即可(假設(shè)你的 OpenResty 安裝目錄為 ?/usr/local/openresty?)。

驗(yàn)證代碼如下:


server {

    listen       8080 default_server;
    server_name  _;

    resolver 8.8.8.8;

    location /baidu {
        content_by_lua_block {
            local http = require "resty.http"
            local httpc = http.new()
            local res, err = httpc:request_uri("http://www.baidu.com")
            if res.status == ngx.HTTP_OK then
                ngx.say(res.body)
            else
                ngx.exit(res.status)
            end
        }
    }
}

訪問 http://127.0.0.1:8080/baidu , 如果出現(xiàn)的是百度的首頁,說明你配置成功了。

當(dāng)然這里也可以自定義 lua_package_path 指定 Lua 的查找路徑,這樣就可以把第三方代碼放到相應(yīng)的位置下,這么做更加方便歸類文件,明確什么類型的文件放到什么地方(比如:公共文件、業(yè)務(wù)文件)。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)