如何用Golang开发简单的留言回复系统_Golang 留言回复系统实战

答案:使用Golang和Gin框架可快速实现留言回复系统,通过Message和Reply结构体定义数据模型,内存存储模拟数据库,设计提交留言、查看留言和添加回复的路由接口,结合HTML模板渲染前端页面,支持留言按时间倒序展示与嵌套回复功能。

用Golang开发一个简单的留言回复系统并不复杂,关键在于理清数据结构、路由设计和前后端交互方式。下面通过一个实战示例,带你一步步实现一个基础但功能完整的留言回复系统。

1. 功能需求与数据结构设计

我们要实现的基本功能包括:

  • 用户提交留言
  • 查看所有留言(按时间倒序)
  • 对某条留言进行回复
  • 支持层级嵌套显示(留言+回复)

定义核心结构体:

type Message struct {
    ID        int       `json:"id"`
    Content   string    `json:"content"`
    Username  string    `json:"username"`
    CreatedAt time.Time `json:"created_at"`
    Replies   []Reply   `json:"replies"`
}

type Reply struct { ID int json:"id" Content string json:"content" Username string json:"username" MessageID int json:"message_id" CreatedAt time.Time json:"created_at" }

使用内存存储模拟数据库,适合快速验证逻辑:

var messages = make(map[int]Message)
var replies = make(map[int][]Reply)
var messageIDCounter = 1
var replyIDCounter = 1

2. 使用Gin搭建HTTP服务

推荐使用 Gin 框架,轻量且性能高。先安装依赖:

go get -u github.com/gin-gonic/gin

初始化路由和服务器:

func main() {
    r := gin.Default()
    r.LoadHTMLGlob("templates/*")
r.GET("/", getMessages)
r.POST("/message", createMessage)
r.POST("/reply", createReply)

r.Run(":8080")

}

3. 实现核心接口

获取所有留言(含回复)

func getMessages(c *gin.Context) {
    var result []Message
    for _, msg := range messages {
        msg.Replies = replies[msg.ID]
        result = append(result, msg)
    }
    // 按时间倒序
    sort.Slice(result, func(i, j int) bool {
        return result[i].CreatedAt.After(result[j].CreatedAt)
    })
    c.HTML(200, "index.html", gin.H{"messages": result})
}

创建新留言

func createMessage(c *gin.Context) {
    var form struct {
        Username string `form:"username" binding:"required"`
        Content  string `form:"content" binding:"required"`
    }
if err := c.ShouldBind(&form); err != nil {
    c.JSON(400, gin.H{"error": err.Error()})
    return
}

msg := Message{
    ID:        messageIDCounter,
    Username:  form.Username,
    Content:   form.Content,
    CreatedAt: time.Now(),
}
messages[messageIDCounter] = msg
messageIDCounter++

c.Redirect(302, "/")

}

添加回复

func createReply(c *gin.Context) {
    var form struct {
        MessageID int    `form:"message_id" binding:"required"`
        Username  string `form:"username" binding:"required"`
        Content   string `form:"content" binding:"required"`
    }
if err := c.ShouldBind(&form); err != nil {
    c.JSON(400, gin.H{"error": err.Error()})
    return
}

reply := Reply{
    ID:        replyIDCounter,
    MessageID: form.MessageID,
    Username:  form.Username,
    Content:   form.Content,
    CreatedAt: time.Now(),
}

replies[form.MessageID] = append(replies[form.MessageID], reply)
replyIDCounter++

c.Redirect(302, "/")

}

4. 编写前端页面(HTML模板)

在项目根目录创建 templates/index.html



留言系统

  

发表留言


所有留言

{{range .messages}}

{{.Username}} ({{.CreatedAt.Format "2006-01-02 15:04"}})

{{.Content}}

  zuojiankuohaophpcn!-- 回复表单 --youjiankuohaophpcn
  zuojiankuohaophpcnform method="post" action="/reply" style="margin:10px 0;"youjiankuohaophpcn
    zuojiankuohaophpcninput type="hidden" name="message_id" value="{{.ID}}" /youjiankuohaophpcn
    zuojiankuohaophpcninput type="text" name="username" placeholder="用户名" required /youjiankuohaophpcn
    zuojiankuohaophpcninput type="text" name="content" placeholder="回复内容" required /youjiankuohaophpcn
    zuojiankuohaophpcnbutton type="submit"youjiankuohaophpcn回复zuojiankuohaophpcn/buttonyoujiankuohaophpcn
  zuojiankuohaophpcn/formyoujiankuohaophpcn

  zuojiankuohaophpcn!-- 显示回复 --youjiankuohaophpcn
  {{range .Replies}}
    zuojiankuohaophpcndiv style="margin-left:20px; font-size:0.9em; color:#555;"youjiankuohaophpcn
      zuojiankuohaophpcnstrongyoujiankuohaophpcn{{.Username}}zuojiankuohaophpcn/strongyoujiankuohaophpcn: {{.Content}} 
      ({{.CreatedAt.Format "15:04"}})
    zuojiankuohaophpcn/divyoujiankuohaophpcn
  {{end}}
zuojiankuohaophpcn/divyoujiankuohaophpcn

{{end}}