mirror of
https://github.com/metosin/reitit.git
synced 2026-02-09 21:13:13 +00:00
Add trailing slash handler
This commit is contained in:
parent
46254975d9
commit
875934360e
1 changed files with 29 additions and 0 deletions
|
|
@ -110,6 +110,35 @@
|
||||||
(respond nil)))]
|
(respond nil)))]
|
||||||
(f handlers))))))
|
(f handlers))))))
|
||||||
|
|
||||||
|
(defn redirect-trailing-slash-handler
|
||||||
|
"A ring handler that redirects a missing path if there is an
|
||||||
|
existing path that only differs in the ending slash.
|
||||||
|
|
||||||
|
| key | description |
|
||||||
|
|---------|-------------|
|
||||||
|
| :method | :add - redirects slash-less to slashed |
|
||||||
|
| | :strip - redirects slashed to slash-less |
|
||||||
|
| | :both - works both ways (default) |
|
||||||
|
"
|
||||||
|
[{:keys [method] :or {method :both}}]
|
||||||
|
(let [redirect-handler (fn redirect-handler [request]
|
||||||
|
(let [uri (:uri request)
|
||||||
|
maybe-redirect (fn maybe-redirect [path]
|
||||||
|
(if (r/match-by-path (::r/router request) path)
|
||||||
|
{:status 308 ; permanent redirect
|
||||||
|
:headers {"Location" path}
|
||||||
|
:body ""}))]
|
||||||
|
(if (str/ends-with? uri "/")
|
||||||
|
(if (not= method :add)
|
||||||
|
(maybe-redirect (subs uri 0 (-> uri count dec))))
|
||||||
|
(if (not= method :strip)
|
||||||
|
(maybe-redirect (str uri "/"))))))]
|
||||||
|
(fn
|
||||||
|
([request]
|
||||||
|
(redirect-handler request))
|
||||||
|
([request respond _]
|
||||||
|
(respond (redirect-handler request))))))
|
||||||
|
|
||||||
(defn create-default-handler
|
(defn create-default-handler
|
||||||
"A default ring handler that can handle the following cases,
|
"A default ring handler that can handle the following cases,
|
||||||
configured via options:
|
configured via options:
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue