go基础留言板系统使用标准库实现:定义Message结构体与内存切片存储,html模板渲染表单及留言列表,http路由处理GET展示与POST提交,提交后重定向防重复,支持xss防护。

用 Go 构建一个基础留言板系统,核心是处理 HTTP 请求(接收表单提交)、存储数据(内存或文件暂存)、再渲染页面展示所有留言。下面以 纯标准库 + HTML 模板 实现一个可运行的最小可行版本,不依赖数据库或框架,适合初学理解流程。
1. 定义留言数据结构与存储
先定义留言结构体,并用切片在内存中暂存(开发调试够用,生产环境应换为 sqlite/postgresql):
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 文件,放在项目根目录:
立即学习“go语言免费学习笔记(深入)”;
留言板 留下你的想法
大家的留言
{{range .}} {{.Username}} {{.CreatedAt.Format "2006-01-02 15:04"}}
{{.Content | html}} {{else}} 暂无留言
{{end}}
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("服务器运行中:https://www.php.cn/link/cbb686245ece57c9827c4bc0d0654a8e") http.ListenAndServe(":8080", nil) }
4. 运行与注意事项
- 确保 index.html 和 main.go 在同一目录
- 运行
go run main.go,打开 https://www.php.cn/link/cbb686245ece57c9827c4bc0d0654a8e - 每次重启程序,留言会清空 —— 如需持久化,可扩展为写入 JSON 文件或接入数据库
- 模板中使用
{{.Content | html}}是为防止 XSS,自动转义 HTML 特殊字符 - 生产环境建议加 csrf 防护、输入长度限制、验证码等,但基础逻辑已清晰呈现