2011-12-05 13 views
7

मिलान करने के लिए कंपोजर रेगेक्स शायद मैं सिर्फ मूर्ख हूं, लेकिन मैं क्लोजर में वैकल्पिक ट्रेलिंग स्लैश के लिए एक मैच सेट नहीं कर सकता।एक पिछला स्लैश

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) 

कंपोज़र में वैकल्पिक पिछला स्लैश मिलान करने के लिए मैं किस रेगेक्स का उपयोग कर सकता हूं?

उत्तर

5

पथ स्ट्रिंग clout आशा के अनुरूप route-matches को पहले तर्क एक regex नहीं है, लेकिन एक स्ट्रिंग है खोजशब्दों और * वाइल्डकार्ड हो सकते हैं।

मेरा मानना ​​है कि 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)) 
+0

आह, मैं मिडलवेयर से बचने के लिए उम्मीद कर रहा था। हालांकि यह एकमात्र तरीका है, तो ठीक है। –

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

बग का समाधान संपादन स्वागत करते हैं।

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))))) 
संबंधित मुद्दे