答案:使用Golang的net/http库实现文章发布系统,定义包含ID、标题、内容、作者和创建时间的Article结构体,通过内存切片存储数据,实现RESTful风格的增删改查接口,支持JSON格式交互,并通过路由分发处理GET、POST、PUT、DELETE请求,适合学习CRUD操作与HTTP服务构建。

要在Golang中实现一个简单的文章发布系统,核心是构建HTTP服务、定义文章数据结构、处理增删改查(CRUD)操作,并可选地使用内存或文件存储。下面是一个轻量但完整的实现思路和代码示例。
每篇文章需要标题、内容、作者和发布时间。使用结构体来表示:
type Article struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Author string `json:"author"`
Created time.Time `json:"created"`
}
用切片在内存中存储文章,适合演示和学习:
var articles []Article var nextID = 1
使用标准库 net/http 启动Web服务,并注册以下接口:
立即学习“go语言免费学习笔记(深入)”;
启动服务器:
func main() {
http.HandleFunc("/articles", handleArticles)
http.HandleFunc("/articles/", handleArticle)
fmt.Println("Server starting on :8080...")
http.ListenAndServe(":8080", nil)
}
根据请求方法分发逻辑。例如,处理获取和创建文章:
func handleArticles(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
json.NewEncoder(w).Encode(articles)
case "POST":
var newArticle Article
if err := json.NewDecoder(r.Body).Decode(&newArticle); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
newArticle.ID = nextID
nextID++
newArticle.Created = time.Now()
articles = append(articles, newArticle)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newArticle)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
处理单篇文章的读取、更新和删除:
func handleArticle(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(strings.TrimPrefix(r.URL.Path, "/articles/"))
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
index := -1
for i, a := range articles {
if a.ID == id {
index = i
break
}
}
if index == -1 {
http.Error(w, "Article not found", http.StatusNotFound)
return
}
switch r.Method {
case "GET":
json.NewEncoder(w).Encode(articles[index])
case "PUT":
var updated Article
if err := json.NewDecoder(r.Body).Decode(&updated); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
articles[index].Title = updated.Title
articles[index].Content = updated.Content
articles[index].Author = updated.Author
json.NewEncoder(w).Encode(articles[index])
case "DELETE":
articles = append(articles[:index], articles[index+1:]...)
w.WriteHeader(http.StatusNoContent)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
使用 curl 或 Postman 测试功能:
curl -X POST -H "Content-Type: application/json" -d '{"title":"Hello","content":"My first post","author":"Tom"}' http://localhost:8080/articles
curl http://localhost:8080/articles
curl http://localhost:8080/articles/1
这个系统目前基于内存存储,重启后数据会丢失。如需持久化,可扩展为写入JSON文件或连接SQLite数据库。
基本上就这些。不复杂但容易忽略的是错误处理和路径解析细节。保持结构清晰,后续扩展模板渲染或前端页面也很方便。
以上就是如何在Golang中实现简单的文章发布系统的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号