reitit/doc/ring/slash_handler.md

69 lines
1.8 KiB
Markdown
Raw Normal View History

2018-10-30 15:10:04 +00:00
# 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 ""}
2018-10-31 17:25:21 +00:00
2018-10-30 15:10:04 +00:00
(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 ""}
2018-10-31 17:25:21 +00:00
2018-10-30 15:10:04 +00:00
(app {:uri "/pong"})
; nil
```
2018-10-31 17:25:21 +00:00
2018-10-30 15:10:04 +00:00
```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
2018-10-31 17:25:21 +00:00
2018-10-30 15:10:04 +00:00
(app {:uri "/pong"})
; {:status 308, :headers {"Location" "/pong/"}, :body ""}
```