首页 > 后端开发 > Golang > 正文

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

P粉602998670
发布: 2025-11-04 02:49:21
原创
320人浏览过
答案:使用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 — 删除文章

启动服务器:

AI新媒体文章
AI新媒体文章

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

AI新媒体文章 75
查看详情 AI新媒体文章
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数据库。

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

以上就是如何在Golang中实现简单的文章发布系统的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号