如何在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 []Articlevar nextID = 1

实现HTTP路由与处理函数

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

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

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1421001.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
如何在Golang中实现动态方法绑定
上一篇 2025年12月16日 14:31:47
如何在Golang中实现抽象工厂模式_Golang抽象工厂模式实现方法汇总
下一篇 2025年12月16日 14:31:56

相关推荐

发表回复

登录后才能评论
关注微信