Skip to content

Commit

Permalink
server: add delete method for routes
Browse files Browse the repository at this point in the history
This patch adds a `httpd:delete(name)` method to delete
named routes.
  • Loading branch information
DerekBum authored and oleg-jukovec committed Sep 12, 2024
1 parent 977a618 commit 125263a
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added

- `roles.httpd` role to configure one or more HTTP servers (#196)
- `httpd:delete(name)` method to delete named routes (#197)

## [1.5.0] - 2023-03-29

Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,13 @@ httpd:route({ path = '/objects', method = 'GET' }, handle3)
...
```
To delete a named route, use `delete()` method of the `httpd` object:
```lua
httpd:route({ path = '/path/to', name = 'route' }, 'controller#action')
httpd:delete('route')
```
The first argument for `route()` is a Lua table with one or more keys:
* `file` - a template file name (can be relative to.
Expand Down
18 changes: 18 additions & 0 deletions http/server.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1260,6 +1260,23 @@ local function add_route(self, opts, sub)
return self
end

local function delete_route(self, name)
local route = self.iroutes[name]
if route == nil then
return
end

self.iroutes[name] = nil
table.remove(self.routes, route)

-- Update iroutes numeration.
for n, r in ipairs(self.routes) do
if r.name then
self.iroutes[r.name] = n
end
end
end

local function url_for_httpd(httpd, name, args, query)

local idx = httpd.iroutes[ name ]
Expand Down Expand Up @@ -1357,6 +1374,7 @@ local exports = {

-- methods
route = add_route,
delete = delete_route,
match = match_route,
helper = set_helper,
hook = set_hook,
Expand Down
37 changes: 37 additions & 0 deletions test/integration/http_server_delete_test.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
local t = require('luatest')
local http_client = require('http.client')

local helpers = require('test.helpers')

local g = t.group()

g.before_each(function()
g.httpd = helpers.cfgserv({
display_errors = true,
})
g.httpd:start()
end)

g.after_each(function()
helpers.teardown(g.httpd)
end)

g.test_delete = function()
local httpd = g.httpd
httpd:route({
path = '/content_type',
name = 'content_type',
}, function()
return {
status = 200,
}
end)

local r = http_client.get(helpers.base_uri .. '/content_type')
t.assert_equals(r.status, 200)

httpd:delete('content_type')

r = http_client.get(helpers.base_uri .. '/content_type')
t.assert_equals(r.status, 404)
end

0 comments on commit 125263a

Please sign in to comment.