博客系统 #
一、系统概述 #
1.1 功能模块 #
- 文章管理
- 评论系统
- 分类标签
- 用户管理
二、数据模型 #
2.1 文章模型 #
go
type Post struct {
ID string `json:"id" gorm:"primaryKey"`
Title string `json:"title"`
Content string `json:"content"`
Summary string `json:"summary"`
AuthorID string `json:"author_id"`
CategoryID string `json:"category_id"`
Status string `json:"status"`
ViewCount int `json:"view_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
2.2 评论模型 #
go
type Comment struct {
ID string `json:"id" gorm:"primaryKey"`
PostID string `json:"post_id"`
UserID string `json:"user_id"`
Content string `json:"content"`
ParentID string `json:"parent_id"`
CreatedAt time.Time `json:"created_at"`
}
三、API实现 #
3.1 文章接口 #
go
posts := app.Group("/posts")
posts.Get("/", func(c *fiber.Ctx) error {
var posts []Post
db.Find(&posts)
return c.JSON(posts)
})
posts.Get("/:id", func(c *fiber.Ctx) error {
var post Post
if err := db.First(&post, "id = ?", c.Params("id")).Error; err != nil {
return c.Status(404).JSON(fiber.Map{"error": "Not found"})
}
return c.JSON(post)
})
posts.Post("/", AuthMiddleware(), func(c *fiber.Ctx) error {
var post Post
if err := c.BodyParser(&post); err != nil {
return c.Status(400).JSON(fiber.Map{"error": err.Error()})
}
post.AuthorID = c.Locals("user_id").(string)
db.Create(&post)
return c.Status(201).JSON(post)
})
四、总结 #
4.1 博客系统要点 #
| 要点 | 说明 |
|---|---|
| 文章管理 | CRUD操作 |
| 评论系统 | 嵌套评论 |
| 分类标签 | 内容组织 |
| 用户权限 | 访问控制 |
4.2 下一步 #
现在你已经掌握了博客系统,接下来让我们学习 实时聊天应用,了解WebSocket实战!
最后更新:2026-03-28