也许我只是个白痴,但我不能在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中的可选尾部斜杠?
答案 0 :(得分:5)
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))
答案 1 :(得分:1)
这是中间件的精简版本,没有依赖关系:
(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)))))
Bug修改编辑欢迎。
答案 2 :(得分:0)
对于那些寻找更加更多压缩解决方案的人来说:)
(defn- with-ignore-trailing-slash [handler]
(fn [request]
(let [uri (request :uri)
clean-uri (str/replace uri #"^(.+?)/+$" "$1")]
(handler (assoc request :uri clean-uri)))))