Golang搭建基础博客评论系统教程
时间:2026-04-02
浏览:281
作者:佚名
本文手把手教你用Golang标准库零依赖搭建一个轻量、可运行的博客评论系统原型:从定义JSON友好的Comment结构体、内存中切片存储数据,到实现符合REST规范的GET获取全部评论和POST创建评论接口,并强调Content-Type头设置与HTTP状态码(如201 Created)的正确使用;通过几行curl命令即可快速测试API,非常适合初学者深入理解Go的net/http路由设计、JSON编解码及基础Web服务开发逻辑,同时为后续集成数据库、增加删改查、验证和跨域等功能打下坚实基础。

用Golang构建一个基础的博客评论系统并不复杂,关键在于合理设计路由、数据结构和存储方式。下面是一个简单的实现示例,使用标准库 net/http 处理请求,内存中存储评论(也可替换为数据库),适合入门学习。
1. 项目结构与依赖
创建项目目录:
blog-comments/├── main.go
└── comments.go
无需外部依赖,仅使用Go标准库即可完成。
2. 定义评论数据结构
在 comments.go 中定义评论模型和存储容器:
package main
type Comment struct {
ID int `json:"id"`
Author string `json:"author"`
Content string `json:"content"`
PostID int `json:"post_id"`
}
var comments = []Comment{}
var nextID = 1
这里使用切片模拟数据库存储,nextID 跟踪下一个评论的ID。
3. 实现HTTP接口
在 main.go 中编写路由和处理函数:
package main
import (
"encoding/json"
"log"
"net/http"
)
func getComments(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(comments)
}
func createComment(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "只允许POST请求", http.StatusMethodNotAllowed)
return
}
var comment Comment
if err := json.NewDecoder(r.Body).Decode(&comment); err != nil {
http.Error(w, "请求数据格式错误", http.StatusBadRequest)
return
}
comment.ID = nextID
nextID++
comments = append(comments, comment)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(comment)
}
func main() {
http.HandleFunc("/comments", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
getComments(w, r)
} else if r.Method == "POST" {
createComment(w, r)
} else {
http.Error(w, "不支持的请求方法", http.StatusMethodNotAllowed)
}
})
log.Println("服务启动在 :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
支持两个接口:
- GET /comments:获取所有评论
- POST /comments:创建新评论
4. 测试API
运行程序:
go run *.go
发送POST请求添加评论:
curl -X POST http://localhost:8080/comments \\
-H "Content-Type: application/json" \\
-d '{"author":"Alice","content":"不错的内容!","post_id":1}'
获取所有评论:
curl http://localhost:8080/comments
返回类似:
[{"id":1,"author":"Alice","content":"不错的内容!","post_id":1}]
基本上就这些。这个例子展示了如何用Golang快速搭建一个可工作的评论系统原型。后续可扩展的功能包括按文章ID过滤评论、删除/编辑评论、加入数据库(如SQLite或PostgreSQL)、表单验证、跨域支持等。不复杂但容易忽略的是状态码和Content-Type的正确设置,这对前端调用很关键。
今天关于《Golang搭建基础博客评论系统教程》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
