首先定义帖子和评论的数据结构,使用Post和Comment结构体存储信息。接着通过net/http注册RESTful路由,实现发帖、获取帖子列表、查看帖子详情及添加评论的接口。业务逻辑上,用全局切片模拟数据库,配合sync.Mutex保证并发安全;创建帖子时校验JSON输入并生成唯一ID,获取帖子时返回列表或指定内容,添加评论前先验证对应帖子存在性,并将评论关联到指定帖子。整体采用分层设计,处理函数与数据操作分离,确保代码清晰可扩展。
实现一个简易的 Go 语言论坛系统,核心在于用户发帖与评论的逻辑设计。重点是数据结构定义、路由处理、业务逻辑分层以及数据库操作。下面从模型设计、接口逻辑到代码组织,一步步说明如何用 Golang 实现这个功能。
论坛最基本的功能是用户发布主题帖和对帖子进行评论。我们需要定义两个主要结构体:
type Post struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Author string `json:"author"` // 可替换为 user_id
CreatedAt time.Time `json:"created_at"`
}
type Comment struct {
ID int json:"id"
PostID int json:"post_id"
Content string json:"content"
Author string json:"author"
CreatedAt time.Time json:"created_at"
}
这些结构体可用于内存存储或映射到数据库表。初期可用 slice + sync.Mutex 模拟持久化,便于快速验证逻辑。
使用 net/http 或 Gin 等框架注册以下 RESTful 风格接口:
示例使用标准库启动服务:
func main() {
http.HandleFunc("/posts", listPosts)
http.HandleFunc("/posts", createPost) // 区分 POST 和 GET
http.HandleFunc("/posts/", getPostWithComments)
log.Println("Server starting on :8080")
http.ListenAndServe(":8080", nil)
}
将处理函数与业务逻辑分离,保持 handler 简洁:
例如创建帖子的 handler:
var posts []Post var currentID = 1 var mu sync.Mutexfunc createPost(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "method not allowed", 405) return }
var req struct { Title string `json:"title"` Content string `json:"content"` Author string `json:"author"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "bad request", 400) return } mu.Lock() defer mu.Unlock() posts = append(posts, Post{ ID: currentID, Title: req.Title, Content: req.Content, Author: req.Author, CreatedAt: time.Now(), }) currentID++ w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]int{"id": currentID - 1})
}
评论依赖于帖子存在。关键点包括:
示例添加评论:
var comments []Comment var commentID = 1func addComment(w http.ResponseWriter, r *http.Request) { // 提取 postID parts := strings.Split(r.URL.Path, "/") postID, _ := strconv.Atoi(parts[2])
// 检查帖子是否存在 exists := false for _, p := range posts { if p.ID == postID { exists = true break } } if !exists { http.Error(w, "post not found", 404) return } var req struct{ Content, Author string } json.NewDecoder(r.Body).Decode(&req) mu.Lock() defer mu.Unlock() comments = append(comments, Comment{ ID: commentID, PostID: postID, Content: req.Content, Author: req.Author, CreatedAt: time.Now(), }) commentID++ w.WriteHeader(201) json.NewEncoder(w).Encode(map[string]int{"comment_id": commentID - 1})}
基本上就这些。通过合理划分结构体、接口和处理流程,Golang 能很清晰地实现一个可运行的简易论坛核心逻辑。后续可扩展用户认证、分页、ORM(如 GORM)、模板渲染等功能。