openroutey

一个 Lua 库,允许 OpenResty(基于 Nginx)动态生成到源服务器的路由

$ opm get matthew1000/openroutey

OpenRoutey

OpenRoutey 是一个 Lua 库,允许 OpenResty(基于 Nginx)动态生成到源服务器(后端)的路由。Openroutey 会参考 JSON 路由定义(可以存储在服务器本地或其他地方)来确定如何路由流量。其他功能包括能够对响应进行转换,以及使用Redis作为响应缓存。

安装

  • 首先,确保已安装 OpenResty。请参阅 https://openresty.org.cn/en/installation.html

  • 可以使用 OpenResty 的包管理器 opm 安装 OpenRoutey

       # Pick an installation directory that's suitable for your environment:
       opm --install-dir="/usr/lib/openresty/lualib" install openroutey

设置

首先,创建一个基本的路由文件。您可以随意命名它 - routes.json 是一个不错的建议。您可以将其放在 OpenResty 可以访问的任何位置 - 例如 /etc/openrsesty/usr/local/etc/openresty

将以下内容添加到文件中

    {
        "routes" : [
            {
                "pathMatch" : "^/",
                "status" : 200,
                "body" : "Hello world"
            }
        ]
    }

这基本上表示“使用文本“Hello world”和 200(OK)响应代码响应所有请求。”(我们将在下面的“JSON 路由定义”中查看更复杂的路由。)

设置 OpenResty

编辑 OpenResty 的 nginx.conf 文件。您可以在 /etc/openresty/usr/local/etc/openresty 中找到它。

在“http”部分中,添加 openroutey 安装的路径,并在末尾添加 /?.lua;;,例如

        lua_package_path "/usr/lib/openresty/lualib/?.lua;;";

然后在其下方,使用以下内容初始化 OpenRoutey

        init_by_lua '
            openroutey = require "openroutey"
            openroutey.init({
                routesFile = "/path/to/routes.json",
                redisHost = "127.0.0.1",
                redisPort = 6379
            })
        ';

/path/to/routes.json 替换为您上面创建的基本路由文件的路径。

然后,在服务器部分中,删除任何现有的 location 条目并添加以下内容

        location ~ ^/call(?<path>/.*) {
            proxy_pass_request_headers off;
    
            #internal; # enable for production env
            proxy_set_header Accept-Encoding ''; # don't accept gzipped responses
            # If you need to set client-side SSL certificates, do it here
            proxy_set_header If-None-Match $arg_etag;
    
            resolver 8.8.8.8; # Change this when on AWS
            set_unescape_uri $domain $arg_domain;
            set_unescape_uri $allargs $arg_allargs;
            proxy_pass $domain$path$allargs;
        }
    
        location / {
            lua_code_cache off; # remove when going live
            content_by_lua_block { openroutey.go() }
        }

现在启动 OpenResty

    # Or, reload if already running:
    openresty -s reload

现在访问服务器上的任何 URL。例如,如果您的服务器在本地端口 8000 上运行,请访问 http://localhost:8000/。您应该会收到消息“Hello world”。

JSON 路由定义

路由在 JSON 中定义,上面“Hello world”示例就是一个简单的例子。

待办事项 编写此文档

正则表达式

  • Lua 正则表达式不支持完整的 POSIX 支持。

  • 如果需要在 Lua 正则表达式中提供连字符,请使用 % 进行转义,例如 "^/foo%-bar"

  • 要测试正则表达式,请在命令行上使用 lua,例如

        echo 'print(string.match("foo-bar", "foo%-bar"))' | lua

测试

测试通过 Node.JS 脚本(模拟源服务器)和 Mocha 测试框架完成。

    cd test
    npm install # only needs to be done once
    npm test

作者

Matthew (@matthew1000)

许可证

apache2

版本