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

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))
于 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 に答える