Skip to content

Commit d410fae

Browse files
committed
server: add delete method for routes
This patch adds a `httpd:delete(name)` method to delete named routes.
1 parent 502f76f commit d410fae

File tree

4 files changed

+63
-0
lines changed

4 files changed

+63
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
1313
### Added
1414

1515
- `httpd` role to configure one or more HTTP servers (#196)
16+
- `httpd:delete(name)` method to delete named routes (#197)
1617

1718
## [1.5.0] - 2023-03-29
1819

README.md

+7
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,13 @@ httpd:route({ path = '/objects', method = 'GET' }, handle3)
184184
...
185185
```
186186

187+
To delete a named route, use `delete()` method of the `httpd` object:
188+
189+
```lua
190+
httpd:route({ path = '/path/to', name = 'route' }, 'controller#action')
191+
httpd:delete('route')
192+
```
193+
187194
The first argument for `route()` is a Lua table with one or more keys:
188195

189196
* `file` - a template file name (can be relative to.

http/server.lua

+18
Original file line numberDiff line numberDiff line change
@@ -1260,6 +1260,23 @@ local function add_route(self, opts, sub)
12601260
return self
12611261
end
12621262

1263+
local function delete_route(self, name)
1264+
local route = self.iroutes[name]
1265+
if route == nil then
1266+
return
1267+
end
1268+
1269+
self.iroutes[name] = nil
1270+
table.remove(self.routes, route)
1271+
1272+
-- Update iroutes numeration.
1273+
for n, r in ipairs(self.routes) do
1274+
if r.name then
1275+
self.iroutes[r.name] = n
1276+
end
1277+
end
1278+
end
1279+
12631280
local function url_for_httpd(httpd, name, args, query)
12641281

12651282
local idx = httpd.iroutes[ name ]
@@ -1357,6 +1374,7 @@ local exports = {
13571374

13581375
-- methods
13591376
route = add_route,
1377+
delete = delete_route,
13601378
match = match_route,
13611379
helper = set_helper,
13621380
hook = set_hook,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
local t = require('luatest')
2+
local http_client = require('http.client')
3+
4+
local helpers = require('test.helpers')
5+
6+
local g = t.group()
7+
8+
g.before_each(function()
9+
g.httpd = helpers.cfgserv({
10+
display_errors = true,
11+
})
12+
g.httpd:start()
13+
end)
14+
15+
g.after_each(function()
16+
helpers.teardown(g.httpd)
17+
end)
18+
19+
g.test_delete = function()
20+
local httpd = g.httpd
21+
httpd:route({
22+
path = '/content_type',
23+
name = 'content_type',
24+
}, function()
25+
return {
26+
status = 200,
27+
}
28+
end)
29+
30+
local r = http_client.get(helpers.base_uri .. '/content_type')
31+
t.assert_equals(r.status, 200)
32+
33+
httpd:delete('content_type')
34+
35+
r = http_client.get(helpers.base_uri .. '/content_type')
36+
t.assert_equals(r.status, 404)
37+
end

0 commit comments

Comments
 (0)