7

也许我只是个白痴,但我无法在 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 中的可选斜杠?

4

3 回答 3

5

The path string expected by clout as the first argument to route-matches is not a regex, but a string that can contain keywords and the * wildcard.

I believe clout doesn't natively support defining routes that ignore a trailing slash. You could solve the problem with a middleware function that removes trailing slashes. The following functions were taken from an old version of the compojure source code (before the big refactoring), I couldn't find out if they moved to a new place. Here is the original commit that introduced these functions.

(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))
于 2011-12-05T05:55:48.633 回答
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)))))

欢迎进行错误修复编辑。

于 2014-03-20T01:18:03.967 回答
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)))))
于 2016-03-10T18:53:17.580 回答