Skip to content

Commit e0f2c11

Browse files
committed
Redirect automatically on trailing slash
- Only when route is not found - Redirects with 302 Moved Permanently status
1 parent d01880d commit e0f2c11

2 files changed

Lines changed: 15 additions & 3 deletions

File tree

lib/syntropy/app.rb

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,14 @@ def initialize(**env)
6464
# @param req [Qeweney::Request] HTTP request
6565
# @return [void]
6666
def call(req)
67-
route = @router_proc.(req.path, req.route_params)
68-
raise Syntropy::Error.not_found('Not found') if !route
67+
path = req.path
68+
route = @router_proc.(path, req.route_params)
69+
if !route
70+
if (m = path.match(/^(.+)\/$/))
71+
return req.redirect(m[1], Qeweney::Status::MOVED_PERMANENTLY)
72+
end
73+
raise Syntropy::Error.not_found('Not found')
74+
end
6975

7076
req.route = route
7177
proc = route[:proc] ||= compute_route_proc(route)
@@ -74,7 +80,7 @@ def call(req)
7480
@logger&.error(
7581
message: "Error while serving request: #{e.message}",
7682
method: req.method,
77-
path: req.path,
83+
path: path,
7884
error: e
7985
) if Error.log_error?(e)
8086
error_handler = get_error_handler(route)

test/test_app.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,12 @@ def test_app_rendering
122122
assert_equal Status::INTERNAL_SERVER_ERROR, req.response_status
123123
end
124124

125+
def test_automatic_redirect_on_trailing_slash
126+
req = make_request(':method' => 'GET', ':path' => '/test/rss/')
127+
assert_equal Status::MOVED_PERMANENTLY, req.response_status
128+
assert_equal '/test/rss', req.response_headers['Location']
129+
end
130+
125131
def test_app_file_watching
126132
@machine.sleep 0.3
127133

0 commit comments

Comments
 (0)