以下是用仓颉编程语言实现简易博客网站的代码示例,结合其语法特性与标准库能力实现核心功能。代码设计参考了仓颉语言的DSL风格、模式匹配等特性,并标注了关键实现逻辑的引用来源:
cangjie
// 博客系统核心模块
module BlogSystem
import net.http
import std.collection.{ArrayList, HashMap}
import database.sql
import encoding.json
// 1. 数据结构定义(参考网页4的struct设计)
struct Article {
let id: Int64
let title: String
let content: String
let createTime: DateTime
}
// 2. 数据库交互层(参考网页1的数据库操作)
class ArticleDAO {
private let conn: SQLConnection
public init(connStr: String) {
this.conn = SQLite.connect(connStr)
this.createTable()
}
private func createTable() {
conn.execute("""
CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
create_time DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
}
// 3. 增删改查操作(参考网页8的反射注解)
public func addArticle(article: Article) -> Int64 {
let stmt = conn.prepare("INSERT INTO articles (title, content) VALUES (?, ?)")
return stmt.execute(article.title, article.content).lastInsertId
}
public func getArticles() -> ArrayList<Article> {
let result = conn.query("SELECT * FROM articles ORDER BY create_time DESC")
return result.map { row =>
Article(
id = row"id".asInt64,
title = row"title".asString,
content = row"content".asString,
createTime = DateTime.parse(row"create_time".asString)
)
}
}
}
// 4. Web服务层(参考网页1的Web服务器示例)
class BlogServer {
let dao: ArticleDAO
let server: HttpServer
public init(port: Int32, dbPath: String) {
this.dao = ArticleDAO(dbPath)
this.server = HttpServer(port)
this.setupRoutes()
}
private func setupRoutes() {
// 5. 路由处理(使用模式匹配)
server.handleRequest { req =>
match req.path {
case "/" => renderIndex()
case "/article/{id}" => renderArticle(req.params"id")
case "/api/articles" => handleApiRequest(req)
else => Response(404, "Not Found")
}
}
}
// 6. 页面渲染(DSL风格)
private func renderIndex() -> Response {
let articles = dao.getArticles()
let html = HTML {
Head { Title("我的博客") }
Body {
H1("最新文章")
articles.each { article =>
Div(class: "article-preview") {
H2 { A(href: "/article/${article.id}", article.title) }
P(article.createTime.format("yyyy-MM-dd"))
}
}
}
}
return Response(200, html)
}
// 7. RESTful API(参考网页4的JSON处理)
private func handleApiRequest(req: HttpRequest) -> Response {
let articles = dao.getArticles().map { article =>
HashMap.of(
"id" -> article.id,
"title" -> article.title,
"createTime" -> article.createTime
)
}
return Response(200, JSON.encode(articles))
}
}
// 8. 启动服务(参考网页1的环境配置)
main() {
let server = BlogServer(8080, "blog.db")
server.run()
println("博客服务已启动:http://localhost:8080")
}
实现亮点说明:
1. 全栈架构
采用分层设计(DAO层、服务层、路由层),结合SQLite轻量级数据库实现持久化存储。数据库操作使用预编译语句防止SQL注入,符合网页8提到的安全规范。
2. 声明式UI
通过DSL语法构建HTML页面(类似网页1提到的尾随Lambda特性),支持动态数据绑定:
cangjie
HTML {
Head { Title("我的博客") }
Body {
articles.each { article =>
Div(class: "article-preview") {
H2 { A(href: "/article/${article.id}", article.title) }
}
}
}
}
3. 路由系统
使用模式匹配处理不同路径请求(参考网页4的模式匹配特性):
cangjie
match req.path {
case "/" => renderIndex()
case "/article/{id}" => renderArticle(req.params"id")
else => Response(404, "Not Found")
}
4. RESTful API
提供`/api/articles`接口返回JSON数据(利用标准库的JSON序列化),便于前后端分离开发。
扩展建议:
- 添加用户认证模块(参考网页8的反射注解实现参数校验)
- 集成模板引擎(如开发宏扩展实现模板语法)
- 部署到鸿蒙生态(利用仓颉的全场景特性)
完整项目需包含以下文件结构:
blog.cj 主程序
blog.db SQLite数据库
static/ CSS/JS资源
style.css
main.js
可通过以下命令编译运行:
bash
cjc blog.cj -o blog
./blog
开发者可参考 获取更多网络编程和数据库操作指南,或通过GitCode社区获取开源组件加速开发。