登录
首页 >  Golang >  Go教程

Golang实现留言板系统教程

时间:2026-03-02 13:37:42 115浏览 收藏

本文手把手带你用 Go 语言标准库从零构建一个轻量、安全、可运行的留言板系统:无需第三方框架或数据库,仅靠内置 net/http、html/template 和内存切片,就实现了表单提交、XSS 防护(自动 HTML 转义)、重定向防重复提交、时间格式化与响应式页面渲染等核心功能,代码简洁清晰,特别适合 Go 初学者快速理解 Web 开发全流程——运行即见效果,重启即重置,是深入掌握 HTTP 处理、模板渲染与状态管理的绝佳入门实践。

如何在Golang中构建留言板系统_用户提交留言并展示

用 Go 构建一个基础留言板系统,核心是处理 HTTP 请求(接收表单提交)、存储数据(内存或文件暂存)、再渲染页面展示所有留言。下面以 纯标准库 + HTML 模板 实现一个可运行的最小可行版本,不依赖数据库或框架,适合初学理解流程。

1. 定义留言数据结构与存储

先定义留言结构体,并用切片在内存中暂存(开发调试够用,生产环境应换为 SQLite/PostgreSQL):

(放在 main.go 开头)

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

var messages = make([]Message, 0)
var nextID = 1

2. 编写 HTML 模板(含表单 + 留言列表)

新建 index.html 文件,放在项目根目录:

<!DOCTYPE html>
<html>
<head><title>留言板</title></head>
<body>
  <h2>留下你的想法</h2>
  <form method="POST" action="/submit">
    &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;昵称&quot; required&gt;<br>
    &lt;textarea name=&quot;content&quot; placeholder=&quot;说点什么...&quot; rows=&quot;4&quot; required&gt;&lt;/textarea&gt;<br>
    <button type="submit">提交</button>
  </form>

  <hr>
  <h3>大家的留言</h3>
  {{range .}}
    <div style="margin: 10px 0; padding: 8px; border-left: 3px solid #007bff;">
      <strong>{{.Username}}</strong> <small>{{.CreatedAt.Format "2006-01-02 15:04"}}</small><br>
      {{.Content | html}}
    </div>
  {{else}}
    <p><em>暂无留言</em></p>
  {{end}}
</body>
</html>

3. 实现 HTTP 路由与处理器

在 main.go 中注册两个路由:/(GET,显示页面)和 /submit(POST,接收并保存留言):

func main() {
    // 加载模板
    tmpl := template.Must(template.ParseFiles("index.html"))

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.Method != "GET" {
            http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
            return
        }
        // 渲染模板,传入所有留言
        tmpl.Execute(w, messages)
    })

    http.HandleFunc("/submit", func(w http.ResponseWriter, r *http.Request) {
        if r.Method != "POST" {
            http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
            return
        }

        // 解析表单
        err := r.ParseForm()
        if err != nil {
            http.Error(w, "解析失败", http.StatusBadRequest)
            return
        }

        username := strings.TrimSpace(r.FormValue("username"))
        content := strings.TrimSpace(r.FormValue("content"))

        if username == "" || content == "" {
            http.Error(w, "昵称和内容不能为空", http.StatusBadRequest)
            return
        }

        // 保存新留言
        msg := Message{
            ID:        nextID,
            Username:  username,
            Content:   content,
            CreatedAt: time.Now(),
        }
        messages = append(messages, msg)
        nextID++

        // 提交后重定向到首页,避免重复提交
        http.Redirect(w, r, "/", http.StatusSeeOther)
    })

    fmt.Println("服务器运行中:http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

4. 运行与注意事项

  • 确保 index.htmlmain.go 在同一目录
  • 运行 go run main.go,打开 http://localhost:8080
  • 每次重启程序,留言会清空 —— 如需持久化,可扩展为写入 JSON 文件或接入数据库
  • 模板中使用 {{.Content | html}} 是为防止 XSS,自动转义 HTML 特殊字符
  • 生产环境建议加 CSRF 防护、输入长度限制、验证码等,但基础逻辑已清晰呈现

理论要掌握,实操不能落!以上关于《Golang实现留言板系统教程》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>