使用Go語言開發(fā)任務(wù)待辦清單Web應(yīng)用
在學(xué)習(xí) Go 的過程中,一個(gè)非常適合入門的 Web 項(xiàng)目就是 TodoList(任務(wù)待辦清單)。它功能簡單,但涵蓋了 HTTP 路由、數(shù)據(jù)存儲(chǔ)、前后端交互 等核心知識(shí)點(diǎn)。本篇我們將實(shí)現(xiàn)一個(gè)基于 Go 標(biāo)準(zhǔn)庫 + HTML 模板 的 TodoList 應(yīng)用。
一、項(xiàng)目目標(biāo)
實(shí)現(xiàn)一個(gè)簡易的 任務(wù)待辦清單 Web 應(yīng)用:
- 查看任務(wù)列表
- 添加任務(wù)
- 刪除任務(wù)
- 標(biāo)記任務(wù)完成/未完成
- 數(shù)據(jù)持久化(存儲(chǔ)在 JSON 文件)
二、系統(tǒng)設(shè)計(jì)
數(shù)據(jù)結(jié)構(gòu)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
}
路由設(shè)計(jì)
| 路徑 | 方法 | 功能 |
|---|---|---|
| / | GET | 展示任務(wù)列表 |
| /add | POST | 添加任務(wù) |
| /delete?id= | GET | 刪除任務(wù) |
| /toggle?id= | GET | 切換完成狀態(tài) |
存儲(chǔ)方式
- 使用 JSON 文件存儲(chǔ)所有任務(wù) (
tasks.json) - 每次操作時(shí)更新文件,保證數(shù)據(jù)持久化
三、完整代碼示例
文件名:main.go
package main
import (
"encoding/json"
"html/template"
"net/http"
"os"
"strconv"
"sync"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
}
var (
tasks []Task
dataFile = "tasks.json"
mutex sync.Mutex
)
// 加載任務(wù)
func loadTasks() {
file, err := os.ReadFile(dataFile)
if err != nil {
tasks = []Task{}
return
}
_ = json.Unmarshal(file, &tasks)
}
// 保存任務(wù)
func saveTasks() {
data, _ := json.MarshalIndent(tasks, "", " ")
_ = os.WriteFile(dataFile, data, 0644)
}
// 首頁:顯示任務(wù)列表
func indexHandler(w http.ResponseWriter, r *http.Request) {
tmpl := `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Todo List</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.done { text-decoration: line-through; color: gray; }
</style>
</head>
<body>
<h1>任務(wù)待辦清單 ?</h1>
<form method="POST" action="/add">
<input type="text" name="title" placeholder="輸入任務(wù)..." required>
<button type="submit">添加</button>
</form>
<ul>
{{range .}}
<li>
<a href="/toggle?id={{.ID}}" rel="external nofollow" >
<span class="{{if .Completed}}done{{end}}">{{.Title}}</span>
</a>
<a href="/delete?id={{.ID}}" rel="external nofollow" style="color:red;">[刪除]</a>
</li>
{{end}}
</ul>
</body>
</html>`
t := template.Must(template.New("index").Parse(tmpl))
_ = t.Execute(w, tasks)
}
// 添加任務(wù)
func addHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
title := r.FormValue("title")
if title != "" {
mutex.Lock()
id := 1
if len(tasks) > 0 {
id = tasks[len(tasks)-1].ID + 1
}
tasks = append(tasks, Task{ID: id, Title: title, Completed: false})
saveTasks()
mutex.Unlock()
}
}
http.Redirect(w, r, "/", http.StatusFound)
}
// 刪除任務(wù)
func deleteHandler(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if id, err := strconv.Atoi(idStr); err == nil {
mutex.Lock()
for i, t := range tasks {
if t.ID == id {
tasks = append(tasks[:i], tasks[i+1:]...)
break
}
}
saveTasks()
mutex.Unlock()
}
http.Redirect(w, r, "/", http.StatusFound)
}
// 切換任務(wù)完成狀態(tài)
func toggleHandler(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if id, err := strconv.Atoi(idStr); err == nil {
mutex.Lock()
for i, t := range tasks {
if t.ID == id {
tasks[i].Completed = !tasks[i].Completed
break
}
}
saveTasks()
mutex.Unlock()
}
http.Redirect(w, r, "/", http.StatusFound)
}
func main() {
loadTasks()
http.HandleFunc("/", indexHandler)
http.HandleFunc("/add", addHandler)
http.HandleFunc("/delete", deleteHandler)
http.HandleFunc("/toggle", toggleHandler)
println("服務(wù)器啟動(dòng):http://localhost:8080")
_ = http.ListenAndServe(":8080", nil)
}
四、運(yùn)行效果
啟動(dòng)服務(wù)
go run main.go
瀏覽器訪問 http://localhost:8080
- 輸入任務(wù) → 點(diǎn)擊“添加” → 列表中出現(xiàn)
- 點(diǎn)擊任務(wù)文字 → 切換完成狀態(tài)(加刪除線 ?)
- 點(diǎn)擊
[刪除]→ 刪除任務(wù)
數(shù)據(jù)保存在 tasks.json 文件,重啟服務(wù)數(shù)據(jù)仍然存在。
五、擴(kuò)展方向
- 任務(wù)編輯功能:修改任務(wù)標(biāo)題
- 增加截止日期 / 優(yōu)先級(jí)
- 搜索 & 分類:已完成 / 未完成分組
- 使用前端框架:Vue/React + Go 后端 API
- 替換存儲(chǔ):SQLite/MySQL/Postgres
六、總結(jié)
這個(gè) TodoList Web 應(yīng)用示例,涵蓋了:
- Go 標(biāo)準(zhǔn)庫 net/http 的基本用法
- HTML 模板 渲染動(dòng)態(tài)頁面
- JSON 文件持久化
- 簡單的 并發(fā)控制(sync.Mutex)
是非常好的 Go Web 開發(fā)入門實(shí)戰(zhàn)案例。
到此這篇關(guān)于使用Go語言開發(fā)任務(wù)待辦清單Web應(yīng)用的文章就介紹到這了,更多相關(guān)Go任務(wù)待辦清單應(yīng)用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談Golang中創(chuàng)建一個(gè)簡單的服務(wù)器的方法
golang使用sync.singleflight解決熱點(diǎn)緩存穿透問題
Go并發(fā)編程結(jié)構(gòu)體多字段原子操作示例詳解

