Golang实现CRUD操作的代码示例与问题求助
Golang实现CRUD操作的代码示例与问题求助 我尝试了一个插入函数的CRUD示例,在URL中我显示为http://localhost:8080,但在输出中我得到了Apache Tomcat而不是表单。由于我是Go语言的新手,能否请您帮助我了解如何在URL中显示表单的步骤?
我已附上我的Go文件和模板文件供您参考。
2 回复
根据你的描述,问题很可能是因为你的Go服务没有正确启动,或者端口被其他服务(如Apache Tomcat)占用了。以下是完整的CRUD示例代码,包含表单显示和插入操作:
main.go:
package main
import (
"html/template"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
type Item struct {
ID int
Name string
Price float64
}
var items []Item
var tmpl = template.Must(template.ParseGlob("templates/*"))
func main() {
r := mux.NewRouter()
// 路由配置
r.HandleFunc("/", indexHandler).Methods("GET")
r.HandleFunc("/create", createFormHandler).Methods("GET")
r.HandleFunc("/create", createHandler).Methods("POST")
r.HandleFunc("/edit/{id}", editFormHandler).Methods("GET")
r.HandleFunc("/update/{id}", updateHandler).Methods("POST")
r.HandleFunc("/delete/{id}", deleteHandler).Methods("GET")
// 静态文件服务
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/",
http.FileServer(http.Dir("static"))))
// 启动服务器
println("Server starting at http://localhost:8080")
http.ListenAndServe(":8080", r)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
tmpl.ExecuteTemplate(w, "index.html", items)
}
func createFormHandler(w http.ResponseWriter, r *http.Request) {
tmpl.ExecuteTemplate(w, "create.html", nil)
}
func createHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
name := r.FormValue("name")
price, _ := strconv.ParseFloat(r.FormValue("price"), 64)
newItem := Item{
ID: len(items) + 1,
Name: name,
Price: price,
}
items = append(items, newItem)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
templates/create.html:
<!DOCTYPE html>
<html>
<head>
<title>Create Item</title>
</head>
<body>
<h1>Create New Item</h1>
<form action="/create" method="POST">
<div>
<label>Name:</label>
<input type="text" name="name" required>
</div>
<div>
<label>Price:</label>
<input type="number" step="0.01" name="price" required>
</div>
<button type="submit">Create</button>
</form>
<a href="/">Back to List</a>
</body>
</html>
templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Items List</title>
</head>
<body>
<h1>Items</h1>
<a href="/create">Create New</a>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Actions</th>
</tr>
{{range .}}
<tr>
<td>{{.ID}}</td>
<td>{{.Name}}</td>
<td>{{.Price}}</td>
<td>
<a href="/edit/{{.ID}}">Edit</a>
<a href="/delete/{{.ID}}">Delete</a>
</td>
</tr>
{{end}}
</table>
</body>
</html>
项目结构:
project/
├── main.go
├── go.mod
├── templates/
│ ├── index.html
│ └── create.html
└── static/
└── (可选CSS/JS文件)
go.mod:
module crud-example
go 1.21
require github.com/gorilla/mux v1.8.1
运行步骤:
- 确保8080端口没有被占用:
netstat -ano | findstr :8080(Windows) 或lsof -i :8080(Linux/Mac) - 如果Tomcat占用了端口,停止Tomcat服务或修改Go服务的端口
- 安装依赖:
go mod tidy - 运行程序:
go run main.go - 访问
http://localhost:8080查看表单
如果仍然看到Apache Tomcat,请检查:
- 是否在运行其他Web服务器
- 防火墙或代理设置
- 浏览器缓存(尝试无痕模式)

