Compojureによるルーティング
Compojureを使ってWebルートを定義し、受信したリクエストを特定のハンドラー関数に対応付ける方法を学びます。
「Compojureによるルーティング」はCoddyKit上の無料Clojure Functional Programming & JVM Backend Developmentレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはClojure Functional Programming & JVM Backend Development学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Clojure Functional Programming & JVM Backend Developmentコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
What is Web Routing?
When you type a URL into your browser, how does a web application know which part of its code to run?
This is where routing comes in! Routing is the process of mapping incoming web requests (like visiting a URL) to specific functions or pieces of code that handle them.
- It directs traffic.
- It organizes your application.
- It makes URLs meaningful.
Introducing Compojure
Compojure is a popular routing library for Clojure web applications. It builds on top of Ring, Clojure's web application specification.
Compojure provides simple macros to define routes, making it easy to connect URLs to your handler functions. It helps keep your web application's structure clean and understandable.
Defining a Simple GET Route
Compojure uses macros like GET, POST, PUT, and DELETE to define routes for different HTTP methods. The simplest is GET for fetching data.
Here's how you define a route that responds to requests at the root path /:
(ns my-app.routes
(:require [compojure.core :refer [defroutes GET]]))
(defroutes app-routes
(GET "/" [] "Welcome to Compojure!"))Running a Compojure Application
To make our routes active, we need a web server. We'll use http-kit, a simple and fast server. We wrap our app-routes in a function and start the server.
Try running this complete example. Then open your browser to http://localhost:3000!
(ns my-app.core
(:require [compojure.core :refer [defroutes GET]]
[org.httpkit.server :refer [run-server]]))
(defroutes app-routes
(GET "/" [] "Hello from Compojure!"))
(defn -main [& args]
(println "Starting server on port 3000...")
(run-server app-routes {:port 3000}))
(-main)Capturing Path Parameters
Often, you need to extract dynamic parts from a URL, like an item ID or a username. Compojure lets you do this using path parameters, denoted by a colon (:) followed by the parameter name.
These parameters are then available within your handler function as arguments.
(ns my-app.routes
(:require [compojure.core :refer [defroutes GET]]))
(defroutes user-routes
(GET "/users/:id" [id]
(str "Fetching user: " id))
(GET "/products/:name" [name]
(str "Product details for: " name)))Handling Different HTTP Methods
Web applications don't just fetch data (GET). They also create (POST), update (PUT), and delete (DELETE) resources. Compojure provides specific macros for each.
You can define different behaviors for the same URL path based on the HTTP method used.
(ns my-app.methods
(:require [compojure.core :refer [defroutes GET POST PUT DELETE]]))
(defroutes item-api
(GET "/items/:id" [id] (str "Get item " id))
(POST "/items" [] "Create a new item")
(PUT "/items/:id" [id] (str "Update item " id))
(DELETE "/items/:id" [id] (str "Delete item " id)))Grouping Routes with `routes`
As your application grows, you'll have many routes. Compojure's routes macro lets you group them logically. This makes your routing definition more organized and readable.
You can then combine these grouped routes into your main application handler.
(ns my-app.groups
(:require [compojure.core :refer [defroutes GET POST routes]]))
(def user-routes
(routes
(GET "/users" [] "List all users")
(POST "/users" [] "Create a user")))
(def product-routes
(routes
(GET "/products" [] "List products")
(GET "/products/:id" [id] (str "Product details for " id))))
(defroutes main-app
user-routes
product-routes
(GET "/" [] "Homepage"))Nesting Routes for Structure
For even better organization, especially with API versions or sub-sections, you can nest routes. Compojure allows you to define a common path prefix for a group of routes using context.
This creates a clear hierarchy for your application's endpoints, like /api/v1/users or /admin/dashboard.
(ns my-app.nested
(:require [compojure.core :refer [defroutes GET context]]))
(defroutes api-v1-routes
(context "/api/v1" []
(GET "/users" [] "API v1: List users")
(GET "/products" [] "API v1: List products")))
(defroutes admin-routes
(context "/admin" []
(GET "/dashboard" [] "Admin Dashboard")
(GET "/settings" [] "Admin Settings")))
(defroutes all-app-routes
api-v1-routes
admin-routes
(GET "/" [] "Main site"))Route Matching Order Matters
Compojure processes routes in the order they are defined. The first route that matches an incoming request's path and HTTP method will be used.
- Define more specific routes BEFORE general ones.
- For example,
/users/newshould come before/users/:id.
Otherwise, /users/new might be incorrectly matched by /users/:id, with 'new' being treated as an ID.
Quick Check: Compojure Routes
Consider the following Compojure route definitions:
(defroutes my-app
(GET "/products/latest" [] "Latest Products")
(GET "/products/:id" [id] (str "Product ID: " id))
(GET "/" [] "Homepage"))Which of the following statements are TRUE about these routes?
Recap: Routing with Compojure
In this lesson, you've learned the essentials of web routing and how Compojure simplifies it for Clojure applications:
- Routing maps URLs to handler functions.
- Compojure provides macros (
GET,POST, etc.) to define routes. - You can capture path parameters like
:id. - Routes can be grouped with
routesand nested withcontext. - Order matters: specific routes must come before general ones.
You're now ready to define clear, organized routes for your Clojure web services!
よくある質問
「Compojureによるルーティング」レッスンは無料ですか?
はい。「Compojureによるルーティング」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Clojure Functional Programming & JVM Backend Developmentコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Clojure Functional Programming & JVM Backend Developmentコースには全4レッスンが含まれています。
「Compojureによるルーティング」で何を学びますか?
Compojureを使ってWebルートを定義し、受信したリクエストを特定のハンドラー関数に対応付ける方法を学びます。 ブラウザで直接実行するハンズオンコードでClojure Functional Programming & JVM Backend Developmentを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Clojure Functional Programming & JVM Backend Developmentを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのClojure Functional Programming & JVM Backend Developmentは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「Compojureによるルーティング」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このClojure Functional Programming & JVM Backend Developmentレッスンでコードを書いて実行できますか?
はい。すべてのClojure Functional Programming & JVM Backend Developmentレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- RingとHTTPの基礎入門
- Compojureによるルーティング
- リクエストとレスポンスの処理
- Ringミドルウェア徹底解説