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 "/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 期望作为 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))

关于clojure - 用于匹配尾部斜杠的 Compojure 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380468/

相关文章:

clojure - 为什么我的 clojurescript 宏不起作用

clojure - 获取与项目相关的文件

clojure - 使用 Clojure Spec 从递归定义生成

java - 如何找到运行 Compojure 的网络托管服务

clojure - 打ic 1.0.0-beta1错误

clojure - 如何在另一个文件中使用我项目中的一个文件?

performance - 为什么这个 Clojure Reducers r/fold 没有提供性能优势?

authentication - 在 Clojure Web 应用程序中使用 JSON 请求正文而不是请求参数进行好友身份验证

clojure - Compojure - 未提供所需参数时如何返回 404?

Clojure - Ring uberjar 指定端口