lua-resty-locations

实现 Nginx 风格 location uri 匹配的 Lua 库。

$ opm get hamishforbes/lua-resty-locations

lua-resty-locations

实现 Nginx 风格“location” uri 匹配的 Lua 库。

类似 Nginx 的 location 功能。支持最长前缀匹配、正则表达式匹配、不区分大小写的正则表达式匹配和精确匹配。

  • 首先检查精确匹配,命中后返回。

  • 然后检查前缀匹配,并记住最长的匹配。

    • 如果前缀匹配具有^~修饰符,则搜索返回。

  • 顺序检查正则表达式。

  • 如果没有正则表达式匹配,则返回最长前缀。

概述

    lua_package_path "/path/to/lua-resty-locations/lib/?.lua;;";
    
    init_by_lua_block {
            local locations = require("resty.locations")
            my_locs = locations:new()
    
            -- Prefix match
            local ok, err = my_locs:set("/foo", "/foo")
    
            -- exact match
            local ok, err = my_locs:set("/bar", "= /bar", "=")
    
            -- regex match
            local ok, err = my_locs:set("^/baz", "~ ^/baz", "~")
    
            -- case insensitive regex match
            local ok, err = my_locs:set("^/qux", "~* ^/qux", "~*")
    
            -- prefix match, no regex check
            local ok, err = my_locs:set("/bazfoo", "^~ /bazfoo", "^~")
    }
    
    server {
        listen 80 default_server;
    
        server_name locations;
    
        location / {
            content_by_lua_block {
                local val, err = my_locs:lookup(ngx.var.uri)
                if val then
                    -- do something based on val
                    ngx.say("Matched: ", val)
                else
                    if err then
                        ngx.log(ngx.ERR, err)
                    end
                    ngx.exit(404)
                end
            }
        }
    }

方法

new

语法:my_locations, err = locations:new(size?)

创建一个新的 resty-locations 实例,并带有一个可选的初始大小。

set

语法:ok, err = my_locations:set(key, value, modifier?)

添加一个新的键及其关联的值和修饰符,默认为空字符串以进行前缀匹配。键必须是字符串。失败时返回 false 和错误消息。

修饰符与 Nginx location 功能相同。

  • (空字符串) - 前缀匹配

  • = - 精确匹配

  • ~ - 正则表达式匹配

  • ~* - 不区分大小写的正则表达式匹配

  • ^~ - 前缀匹配,跳过正则表达式

lookup

语法:val, err = my_locations:lookup(uri)

检索提供的 uri 的值。失败时返回 nil 和错误消息。

作者

Hamish Forbes

许可证

mit

版本