Middleware Ring w praktyce
Dowiedz się, jak middleware Ring opakowuje handlery, aby dodawać przekrojowe funkcje, takie jak logowanie, parsowanie parametrów i obsługa sesji w aplikacjach webowych Compojure.
Middleware Ring w praktyce to bezpłatna lekcja Clojure Functional Programming & JVM Backend Development na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Clojure Functional Programming & JVM Backend Development, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Clojure Functional Programming & JVM Backend Development zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
What Is Middleware?
In Ring, a handler is a function that takes a request map and returns a response map. Middleware is a higher-order function that takes a handler and returns a new handler.
This lets you wrap behavior around your core logic without modifying it.
(defn wrap-example [handler]
(fn [request]
(handler request)))The Wrapping Pattern
Every middleware follows the same shape: receive a handler, return a function that takes a request. You can act before or after calling the inner handler.
- Before: inspect or modify the request
- After: inspect or modify the response
(defn wrap-logging [handler]
(fn [request]
(println "Incoming:" (:uri request))
(let [response (handler request)]
(println "Status:" (:status response))
response)))Applying Middleware
You apply middleware by calling it on your handler. The result is a new handler that you pass to the server.
(def app
(-> handler
wrap-logging))The Threading Macro
The -> threading macro is the idiomatic way to stack middleware. Each layer wraps the one before it.
Order matters: the last middleware listed is the outermost layer that sees the request first.
(def app
(-> routes
wrap-params
wrap-session
wrap-logging))Built-in Middleware
The ring-defaults library bundles common middleware so you do not write it by hand.
- wrap-params parses query and form params
- wrap-session manages sessions
- wrap-keyword-params turns string keys into keywords
(require '[ring.middleware.defaults :refer [wrap-defaults site-defaults]])
(def app
(wrap-defaults routes site-defaults))Modifying the Request
To add data for downstream handlers, assoc a key onto the request before calling the inner handler.
(defn wrap-user [handler]
(fn [request]
(let [user (lookup-user (:session request))]
(handler (assoc request :current-user user)))))Modifying the Response
To set headers or transform output, work on the response after calling the inner handler.
(defn wrap-content-type [handler]
(fn [request]
(let [response (handler request)]
(assoc-in response [:headers "Content-Type"] "text/html"))))Conditional Middleware
Sometimes you only want middleware on certain routes. You can apply it selectively rather than globally.
(defroutes app
(GET "/public" [] public-handler)
(-> (GET "/admin" [] admin-handler)
wrap-authentication))Exception Handling Middleware
A common pattern is wrapping all handlers in a try/catch to return a clean 500 response instead of leaking stack traces.
(defn wrap-errors [handler]
(fn [request]
(try
(handler request)
(catch Exception e
{:status 500 :body "Internal Server Error"}))))Order of Execution
Think of middleware as an onion. The request travels inward through each layer to the handler, then the response travels outward back through them.
- Outermost middleware runs first on request, last on response
- Innermost runs last on request, first on response
; request: wrap-logging -> wrap-session -> wrap-params -> handler
; response: handler -> wrap-params -> wrap-session -> wrap-loggingComposing Reusable Middleware
Because middleware are just functions, you can group them into a single composed function and reuse it across multiple apps.
(defn wrap-common [handler]
(-> handler
wrap-logging
wrap-errors
wrap-params))Quick Check
Test your understanding of middleware ordering.
Recap
You learned that middleware are higher-order functions wrapping handlers to add cross-cutting behavior.
- They can modify the request before, or the response after
- The
->macro stacks them like an onion - Libraries like
ring-defaultsbundle common ones
Next you can combine custom middleware with Compojure routes for full-featured apps.
Często zadawane pytania
Czy lekcja „Middleware Ring w praktyce” jest bezpłatna?
Tak — pełny tekst „Middleware Ring w praktyce” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Clojure Functional Programming & JVM Backend Development, przejdź na CoddyKit PRO. Kurs Clojure Functional Programming & JVM Backend Development zawiera 4 lekcji w sumie.
Co nauczysz się w „Middleware Ring w praktyce”?
Dowiedz się, jak middleware Ring opakowuje handlery, aby dodawać przekrojowe funkcje, takie jak logowanie, parsowanie parametrów i obsługa sesji w aplikacjach webowych Compojure. Ćwiczysz Clojure Functional Programming & JVM Backend Development z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Clojure Functional Programming & JVM Backend Development?
Nie wymagamy żadnego doświadczenia. Clojure Functional Programming & JVM Backend Development w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Middleware Ring w praktyce”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Clojure Functional Programming & JVM Backend Development?
Tak. Każda lekcja Clojure Functional Programming & JVM Backend Development zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Wprowadzenie do Ring i podstaw HTTP
- Routing z Compojure
- Obsługa żądań i odpowiedzi
- Middleware Ring w praktyce