Clojure Web 开发从零开始(一):第一个 Clojure 应用程序
本文记录了从零开始搭建一个最基础的 Clojure 应用程序的过程:环境准备、创建项目文件、编写入口函数、运行与打包,帮助你快速完成“从无到有”的第一步。
1. 项目准备
- 安装 Java SDK
- 下载 leiningen(Lein 项目管理工具),将脚本放入
PATH(例如~/bin):
https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein - 赋予可执行权限:
chmod a+x ~/bin/lein - 测试是否安装成功:
java -version lein
2. 新建项目目录并初始化 Git
mkdir clj-httpbin
cd clj-httpbin
git init
3. 创建项目文件 project.clj
在项目根目录创建 project.clj,内容如下:
(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"}
:dependencies [[org.clojure/clojure "1.10.1"]])
启动 REPL 以确认环境就绪:
lein repl ; 测试 Clojure REPL 正常运行
4. 建立第一个源码文件
创建源码文件 src/clj_httpbin/core.clj:
(ns clj-httpbin.core)
(defn -main []
(println "Hello, World!"))
5. 添加程序入口
在 project.clj 的 :dependencies 之前添加 :main 指定入口命名空间:
:main clj-httpbin.core
运行程序以测试:
lein run
6. 生成可执行 JAR
为了生成可执行 JAR,需要在命名空间中启用 :gen-class。将 src/clj_httpbin/core.clj 第一行:
(ns clj-httpbin.core)
改为:
(ns clj-httpbin.core
(:gen-class))
然后执行打包命令:
lein uberjar
完成后,在 target/ 目录下会看到两个 JAR:
clj-httpbin-0.1.0.jarclj-httpbin-0.1.0-standalone.jar(可执行)
运行 standalone JAR:
java -jar target/clj-httpbin-0.1.0-standalone.jar
如果一切正常,你会看到输出:
Hello, World!
到此,我们已经完成了最基本的 Clojure 程序结构。接下来可以在此基础上逐步扩展功能。
- 下一篇:Clojure Web 开发从零开始 (二)(路由、简单 Web 服务器等)