也许我只是个笨蛋,但我不能在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中,我可以使用什么正则表达式来匹配可选的尾部斜杠?
发布于 2011-12-05 13:55:49
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))发布于 2014-03-20 09:18:04
以下是没有依赖项的中间件的精简版本:
(defn with-ignore-trailing-slash [handler] (fn [request]
(let [uri (request :uri)
clean-uri (if (and (not= "/" uri) (.endsWith uri "/"))
(subs uri 0 (- (count uri) 1))
uri)]
(handler (assoc request :uri clean-uri)))))欢迎使用错误修复编辑。
发布于 2016-03-11 02:53:18
对于那些正在寻找更压缩的解决方案的人:)
(defn- with-ignore-trailing-slash [handler]
(fn [request]
(let [uri (request :uri)
clean-uri (str/replace uri #"^(.+?)/+$" "$1")]
(handler (assoc request :uri clean-uri)))))https://stackoverflow.com/questions/8380468
复制相似问题