Clojure 用于匹配尾部斜杠的Compojure正则表达式

Clojure 用于匹配尾部斜杠的Compojure正则表达式,clojure,compojure,Clojure,Compojure,也许我只是个白痴,但我不能在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 "/artic

也许我只是个白痴,但我不能在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期望作为路由匹配的第一个参数的路径字符串不是正则表达式,而是可以包含关键字和
*
通配符的字符串

我相信
clout
本身不支持定义忽略尾部斜杠的路由。您可以使用删除尾部斜杠的中间件函数来解决这个问题。以下函数取自
compojure
源代码的旧版本(在大重构之前),我无法确定它们是否转移到了新的地方。下面是介绍这些函数的示例

(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))

下面是中间件的精简版本,没有依赖项:

(带有忽略尾部斜杠[handler]的defn)(fn[request]
(let[uri(请求:uri)
清除uri(如果(和(非=“/”uri)(.endsWith uri/))
(子uri 0(-(计数uri)1))
(uri)]
(处理程序(关联请求:uri clean uri()())))

欢迎进行Bug修复编辑。

对于那些寻求更为压缩的解决方案的人:)


啊,我是希望避免。如果这是唯一的办法,那好吧。
(defn- with-ignore-trailing-slash [handler]
  (fn [request]
    (let [uri (request :uri)
          clean-uri (str/replace uri #"^(.+?)/+$" "$1")]
      (handler (assoc request :uri clean-uri)))))