0Pricing
Clojure Functional Programming & JVM Backend Development · 课时

使用 Compojure 进行路由

学习使用 Compojure 定义 Web 路由,并将传入请求匹配到特定的处理函数。

使用 Compojure 进行路由 是 CoddyKit 上的免费 Clojure Functional Programming & JVM Backend Development 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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/new should 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 routes and nested with context.
  • 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 进行路由」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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,全天候 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 反馈 — 无需本地设置。

此课程中的所有课时

  1. Ring 与 HTTP 基础入门
  2. 使用 Compojure 进行路由
  3. 处理请求与响应
  4. 深入理解 Ring 中间件
← 返回 Clojure Functional Programming & JVM Backend Development