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

Kev*_*rke 7 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 "/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)
Run Code Online (Sandbox Code Playgroud)

我可以使用什么正则表达式来匹配Compojure中的可选尾部斜杠?

Chr*_*erg 5

clout作为第一个参数的预期路径字符串route-matches不是正则表达式,而是可以包含关键字和*通配符的字符串.

我相信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))
Run Code Online (Sandbox Code Playgroud)