如何在Golang中实现简单的文章发布系统

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

如何在Golang中实现简单的文章发布系统

要在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 

实现HTTP路由与处理函数

使用标准库 net/http 启动Web服务,并注册以下接口:

立即学习go语言免费学习笔记(深入)”;

  • GET /articles — 获取所有文章
  • GET /articles/:id — 获取指定文章
  • POST /articles — 发布新文章
  • PUT /articles/:id — 更新文章
  • DELETE /articles/:id — 删除文章

启动服务器:

如何在Golang中实现简单的文章发布系统

AI新媒体文章

专为新媒体人打造的ai写作工具,提供“选题创作”、“文章重写”、“爆款标题”等功能

如何在Golang中实现简单的文章发布系统 75

查看详情 如何在Golang中实现简单的文章发布系统

 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)     } } 

测试你的API

使用 curlpostman 测试功能:

  • 发布文章:
    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数据库

基本上就这些。不复杂但容易忽略的是错误处理和路径解析细节。保持结构清晰,后续扩展模板渲染或前端页面也很方便。

暂无评论

发送评论 编辑评论


				
上一篇
下一篇
text=ZqhQzanResources