先创建HTTP服务器并注册路由,定义留言结构体与内存存储,通过表单提交添加留言,使用html/template渲染页面,最终实现一个可展示和提交留言的Web应用。

开发一个留言板应用在Golang中是一个很好的入门项目,能帮助你掌握HTTP服务、路由处理、数据存储和模板渲染等核心技能。下面是一个简单但完整的实现思路和步骤。
Go语言内置了强大的net/http包,可以快速启动一个Web服务器。
先创建一个main函数,注册路由并启动服务:
package main
import (
"net/http"
)
func main() {
http.HandleFunc("/", listMessages)
http.HandleFunc("/add", addMessage)
http.ListenAndServe(":8080", nil)
}
这里注册了两个接口:显示留言列表和添加新留言。
立即学习“go语言免费学习笔记(深入)”;
留言板的核心是消息内容。我们可以用一个结构体来表示一条留言:
type Message struct {
ID int
Name string
Content string
}
为了简化,使用切片作为临时存储(生产环境建议用数据库):
var messages = []Message{}
var nextID = 1
每次添加新留言时递增ID。
addMessage函数负责接收POST请求中的表单数据,并保存到内存中:
func addMessage(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
name := r.FormValue("name")
content := r.FormValue("content")
messages = append(messages, Message{
ID: nextID,
Name: name,
Content: content,
})
nextID++
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
// 如果不是POST,跳转到首页
http.Redirect(w, r, "/", http.StatusFound)
}
使用Go的html/template包来渲染页面:
创建一个templates/index.html文件:
<h1>留言板</h1>
<form action="/add" method="post">
<input type="text" name="name" placeholder="你的名字" required><br>
<textarea name="content" placeholder="写下留言" required></textarea><br>
<button type="submit">提交</button>
</form>
<h2>所有留言</h2>
{{range .}}
<div style="border-bottom:1px solid #ccc;padding:10px;">
<strong>{{.Name}}</strong> (ID: {{.ID}})<br>
{{.Content}}
</div>
{{end}}
然后在listMessages中加载并执行模板:
func listMessages(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/index.html"))
tmpl.Execute(w, messages)
}
确保目录结构如下:
运行程序:
go run main.go访问 http://localhost:8080 即可看到留言板界面。
基本上就这些。功能完整且易于理解。你可以在此基础上扩展:加入删除功能、使用SQLite存储、添加时间戳、支持CSS美化页面等。Go的简洁性让这类小项目非常高效。
以上就是如何在Golang中开发留言板应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号