This commit is contained in:
Unknown 2018-10-31 00:10:04 +09:00
parent da29203cc8
commit 1fc4fc7f60
2 changed files with 65 additions and 0 deletions

View file

@ -25,6 +25,7 @@
["Ring-router" {:file "doc/ring/ring.md"}]
["Reverse-routing" {:file "doc/ring/reverse_routing.md"}]
["Default handler" {:file "doc/ring/default_handler.md"}]
["Slash handler" {:file "doc/ring/slash_handler.md"}]
["Static Resources" {:file "doc/ring/static.md"}]
["Dynamic Extensions" {:file "doc/ring/dynamic_extensions.md"}]
["Data-driven Middleware" {:file "doc/ring/data_driven_middleware.md"}]

64
doc/ring/slash_handler.md Normal file
View file

@ -0,0 +1,64 @@
# Slash handler
The router works with precise matches. If a route is defined without a trailing slash, for example, it won't match a request with a slash.
```clj
(require '[reitit.ring :as ring])
(def app
(ring/ring-handler
(ring/router
["/ping" (constantly {:status 200, :body ""})])))
(app {:uri "/ping/"})
; nil
```
Sometimes it is desirable that paths with and without a trailing slash are recognized as the same.
Setting the `redirect-trailing-slash-handler` as a second argument to `ring-handler`:
```clj
(def app
(ring/ring-handler
(ring/router
[["/ping" (constantly {:status 200, :body ""})]
["/pong/" (constantly {:status 200, :body ""})]])
(ring/redirect-trailing-slash-handler)))
(app {:uri "/ping/"})
; {:status 308, :headers {"Location" "/ping"}, :body ""}
(app {:uri "/pong"})
; {:status 308, :headers {"Location" "/pong/"}, :body ""}
```
`redirect-trailing-slash-handler` accepts an optional `:method` parameter that allows configuring how (whether) to handle missing/extra slashes. The default is to handle both.
```clj
(def app
(ring/ring-handler
(ring/router
[["/ping" (constantly {:status 200, :body ""})]
["/pong/" (constantly {:status 200, :body ""})]])
; only handle extra trailing slash
(ring/redirect-trailing-slash-handler {:method :strip})))
(app {:uri "/ping/"})
; {:status 308, :headers {"Location" "/ping"}, :body ""}
(app {:uri "/pong"})
; nil
```
```clj
(def app
(ring/ring-handler
(ring/router
[["/ping" (constantly {:status 200, :body ""})]
["/pong/" (constantly {:status 200, :body ""})]])
; only handle missing trailing slash
(ring/redirect-trailing-slash-handler {:method :add})))
(app {:uri "/ping/"})
; nil
(app {:uri "/pong"})
; {:status 308, :headers {"Location" "/pong/"}, :body ""}
```