47 |
48 |
custom-matcher.lua
49 |
50 | local Router = require "radix-router"
51 |
52 | local ip_matcher = {
53 | process = function(route)
54 | if route.ips then
56 | local ips = {}
57 | for _, ip in ipairs(route.ips) do
58 | ips[ip] = true
59 | end
60 | route.ips = ips
61 | end
62 | end,
63 | match = function(route, ctx, matched)
64 | if route.ips then
65 | local ip = ctx.ip
66 | if not route.ips[ip] then
67 | return false
68 | end
69 | if matched then
70 | matched["ip"] = ip
71 | end
72 | end
73 | return true
74 | end
75 | }
76 |
77 | local opts = {
78 | matchers = { ip_matcher }, matcher_names = { "method" }, }
81 |
82 | local router = Router.new({
83 | {
84 | paths = { "/" },
85 | methods = { "GET", "POST" },
86 | ips = { "127.0.0.1", "127.0.0.2" },
87 | handler = "1",
88 | },
89 | {
90 | paths = { "/" },
91 | methods = { "GET", "POST" },
92 | ips = { "192.168.1.1", "192.168.1.2" },
93 | handler = "2",
94 | }
95 | }, opts)
96 | assert("1" == router:match("/", { method = "GET", ip = "127.0.0.2" }))
97 | local matched = {}
98 | assert("2" == router:match("/", { method = "GET", ip = "192.168.1.2" }, nil, matched))
99 | print(matched.method) print(matched.ip)
101 |
102 |
103 |