Clojure Web 开发从零开始(二):简单 Web 应用

上一篇文章里,我们已经建立了一个基本的 Clojure 程序,并且编译成了可执行的 Jar 包。
这一篇,我们要把这个 Clojure 应用程序变成一个 HTTP 服务器。


1. 添加 Clojure 库 http-kit

project.clj:dependencies 部分加入:

[http-kit "2.3.0"]

完整文件如下:

(defproject clj-httpbin "0.1.0"
  :description "Clojure httpbin clone"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :main clj-httpbin.core
  :dependencies [[org.clojure/clojure "1.10.1"]
                 [http-kit "2.3.0"]])

2. 下载 http-kit 库

执行命令:

lein deps  ; 自动下载所有库

依赖会存放在 ~/.m2/repository(Maven 本地仓库)。
查看依赖树:

lein deps :tree

3. 最简单的 Web App

定义一个 app 函数来处理 HTTP 请求并返回响应:

(defn app [req]
  {:status 200
   :headers {"Content-Type" "text/html"}
   :body "Hello HTTP!"})

启动 HTTP Server:

(http/run-server app {:port 8080})

完整的 core.clj 文件如下:

(ns clj-httpbin.core
  (:require [org.httpkit.server :as http])
  (:gen-class))

(defn app [req]
  {:status 200
   :headers {"Content-Type" "text/html"}
   :body "Hello HTTP!"})

(defn -main []
  (println "Hello, World!")
  (http/run-server app {:port 8080})
  (println "Server started on port 8080 ..."))

4. 运行程序

启动应用:

lein run

测试服务:

curl -i http://localhost:8080

输出结果:

HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 11
Server: http-kit
Date: Wed, 24 Jul 2019 23:55:08 GMT

Hello HTTP!

至此,我们已经完成了一个最简单的 Clojure Web 应用。
下一篇将进一步扩展功能。