信息发布→ 登录 注册 退出

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

发布时间:2025-11-04

点击量:
答案:使用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

实现HTTP路由与处理函数

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

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

启动服务器:

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

使用 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数据库。

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

标签:# js  # 前端  # json  # go  # golang  # app  # usb  # curl  # ai  # switch  # 路由  # 标准库  # restful  # postman  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!