也许我只是个白痴,但我无法在 Clojure 中为可选的尾部斜杠设置匹配。
lein repl
REPL started; server listening on localhost port 47383
user=> (use 'ring.mock.request 'clout.core)
nil
user=> (route-matches "/article/" (request :get "/article/"))
{}
user=> (route-matches "/article/?" (request :get "/article"))
nil
user=> (route-matches "/article/?" (request :get "/article/"))
nil
user=> (route-matches #"/article/?" (request :get "/article/"))
java.lang.IllegalArgumentException: No implementation of method: :route-matches of protocol: #'clout.core/Route found for class: java.util.regex.Pattern (NO_SOURCE_FILE:0)
我可以使用什么正则表达式来匹配 Compojure 中的可选尾部斜杠?
最佳答案
clout
期望作为 route-matches
第一个参数的路径字符串不是正则表达式,而是可以包含关键字和 *
通配符。
我相信clout
本身并不支持定义忽略尾部斜杠的路由。您可以使用删除尾部斜杠的中间件函数来解决该问题。以下函数取自旧版本的compojure
源代码(在大重构之前),我无法确定它们是否移动到了新的地方。这是original commit介绍了这些功能。
(defn with-uri-rewrite
"Rewrites a request uri with the result of calling f with the
request's original uri. If f returns nil the handler is not called."
[handler f]
(fn [request]
(let [uri (:uri request)
rewrite (f uri)]
(if rewrite
(handler (assoc request :uri rewrite))
nil))))
(defn- uri-snip-slash
"Removes a trailing slash from all uris except \"/\"."
[uri]
(if (and (not (= "/" uri))
(.endsWith uri "/"))
(chop uri)
uri))
(defn ignore-trailing-slash
"Makes routes match regardless of whether or not a uri ends in a slash."
[handler]
(with-uri-rewrite handler uri-snip-slash))
关于clojure - 用于匹配尾部斜杠的 Compojure 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380468/