Go简易博客系统应基于net/http和database/sql手写实现:用结构体封装路由便于测试与扩展中间件;原生SQL控制slug生成、时间字段等细节;开发期用FileServer和ParseFiles提升效率;必须处理所有错误并注意Rows.Close()等易漏细节。
Go 本身不内置 Web 框架或 ORM,所谓“简易博客系统”必须自己选型组合,否则连数据库存文章都得手写 SQL 字符串拼接。
用 net/http 而不是第三方框架起步
新手容易一上来就装 gin 或 echo,但博客核心逻辑简单(列表、详情、新增),net/http 完全够用,且能看清请求生命周期。路由别写死在 http.HandleFunc 里,封装成结构体方法更易测试:
type BlogHandler struct {
db *sql.DB
}
func (h *BlogHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
h.listPosts(w, r)
case "/post":
if r.Method == "GET" {
h.showPost(w, r)
} else if r.Method == "POST" {
h.createPost(w, r)
}
}
}
这样后续加中间件(如登录校验)也只改 ServeHTTP 即可,不用动每个 handler 函数。
用 database/sql + 原生 SQL 管理文章数据
别碰 gorm 这类全自动 ORM——它会让字段映射、时间类型、NULL 处理变成黑盒,而博客的 created_at、updated_at、slug 生成等细节恰恰需要显式控制。示例插入逻辑:
_, err := db.Exec(
"INSERT INTO posts(title, slug, content, created_at) VALUES(?, ?, ?, ?)",
title, slug, content, time.Now().UTC(),
)
注意点: