From 246dc67c7a24077db59e4e04300e246cbc0ccc49 Mon Sep 17 00:00:00 2001 From: DerekBum Date: Sat, 7 Sep 2024 19:18:52 +0300 Subject: [PATCH] server: add `delete` method for routes This patch adds a `httpd:delete(name)` method to delete named routes. --- CHANGELOG.md | 1 + README.md | 7 +++++++ http/server.lua | 18 ++++++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b5f00d3..601dd2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Added - `http_server` role to configure one or more HTTP servers (#196) +- `httpd:delete(name)` method to delete named routes (#197) ## [1.5.0] - 2023-03-29 diff --git a/README.md b/README.md index 7446a6b..5f24171 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/http/server.lua b/http/server.lua index 286be38..facee94 100644 --- a/http/server.lua +++ b/http/server.lua @@ -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 ] @@ -1357,6 +1374,7 @@ local exports = { -- methods route = add_route, + delete = delete_route, match = match_route, helper = set_helper, hook = set_hook,