Go / 系统课时
接好任务 API 的路由与 JSON
接好任务 API 的路由与 JSON
这一课把内存任务仓库接到 net/http:使用 Go 1.22+ 的方法感知 ServeMux 路由完成 CRUD,统一解码和编码 JSON,并把输入错误映射为 400、资源不存在映射为 404,让客户端能按状态码采取不同处理。
学习目标
- 用 Go 1.22+
ServeMux注册带 HTTP 方法和路径参数的 CRUD 路由。 - 限制并校验 JSON 请求体,统一输出 JSON 响应。
- 明确区分 201、204、400、404 和 405 的语义,并用请求验证。
先固定路由与状态码
示例使用 Go 1.22+,因为 GET /tasks/{id} 这类方法感知模式和 r.PathValue("id") 属于这一套路由能力。相同路径存在其他方法模式时,请求方法不匹配由 ServeMux 返回 405;业务参数错误和仓库的 not found 则由处理函数分别返回 400、404。
| 方法与路径 | 行为 | 成功状态 |
|---|---|---|
GET /tasks |
列出任务 | 200 |
POST /tasks |
创建任务 | 201 |
GET /tasks/{id} |
查询单个任务 | 200 |
PUT /tasks/{id} |
完整更新标题与完成状态 | 200 |
DELETE /tasks/{id} |
删除任务 | 204 |

先把“路由匹配失败”和“业务处理失败”分开,后面的处理函数就只关心解码、校验和仓库错误,不需要自己写一大段 method switch。
完成可运行 CRUD 服务
下面是单文件可运行版本,只依赖标准库。请求体上限设为 64 KiB,DisallowUnknownFields 会拒绝拼错字段,第二次 Decode 用来确保一个请求体里只有一个 JSON 对象。列表按 ID 排序,便于测试得到稳定结果。
package main
import (
"encoding/json"
"errors"
"io"
"log"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// ErrNotFound is translated to HTTP 404 by handlers.
var ErrNotFound = errors.New("task not found")
type Task struct {
ID string `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
type Repository struct {
mu sync.RWMutex
tasks map[string]Task
nextID int
}
func NewRepository() *Repository {
return &Repository{tasks: make(map[string]Task)}
}
func (r *Repository) Create(title string) Task {
// ID allocation and map insertion share one lock so concurrent POSTs cannot duplicate IDs.
r.mu.Lock()
defer r.mu.Unlock()
r.nextID++
task := Task{ID: "task-" + strconv.Itoa(r.nextID), Title: title}
r.tasks[task.ID] = task
return task
}
func (r *Repository) List() []Task {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]Task, 0, len(r.tasks))
for _, task := range r.tasks {
out = append(out, task)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
func (r *Repository) Get(id string) (Task, error) {
r.mu.RLock()
defer r.mu.RUnlock()
task, ok := r.tasks[id]
if !ok {
return Task{}, ErrNotFound
}
return task, nil
}
func (r *Repository) Update(id, title string, done bool) (Task, error) {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.tasks[id]; !ok {
return Task{}, ErrNotFound
}
task := Task{ID: id, Title: title, Done: done}
r.tasks[id] = task
return task, nil
}
func (r *Repository) Delete(id string) error {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.tasks[id]; !ok {
return ErrNotFound
}
delete(r.tasks, id)
return nil
}
type App struct {
repo *Repository
}
type createTaskInput struct {
Title string `json:"title"`
}
type updateTaskInput struct {
Title string `json:"title"`
Done bool `json:"done"`
}
func (a *App) routes() http.Handler {
// Method-aware patterns and PathValue require Go 1.22 or newer.
mux := http.NewServeMux()
mux.HandleFunc("GET /tasks", a.listTasks)
mux.HandleFunc("POST /tasks", a.createTask)
mux.HandleFunc("GET /tasks/{id}", a.getTask)
mux.HandleFunc("PUT /tasks/{id}", a.updateTask)
mux.HandleFunc("DELETE /tasks/{id}", a.deleteTask)
return mux
}
func (a *App) listTasks(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, a.repo.List())
}
func (a *App) createTask(w http.ResponseWriter, r *http.Request) {
// Decode transport input first, then perform domain validation.
var in createTaskInput
if err := decodeJSON(w, r, &in); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
in.Title = strings.TrimSpace(in.Title)
if in.Title == "" {
writeError(w, http.StatusBadRequest, "title is required")
return
}
writeJSON(w, http.StatusCreated, a.repo.Create(in.Title))
}
func (a *App) getTask(w http.ResponseWriter, r *http.Request) {
task, err := a.repo.Get(r.PathValue("id"))
if errors.Is(err, ErrNotFound) {
writeError(w, http.StatusNotFound, ErrNotFound.Error())
return
}
writeJSON(w, http.StatusOK, task)
}
func (a *App) updateTask(w http.ResponseWriter, r *http.Request) {
var in updateTaskInput
if err := decodeJSON(w, r, &in); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
in.Title = strings.TrimSpace(in.Title)
if in.Title == "" {
writeError(w, http.StatusBadRequest, "title is required")
return
}
task, err := a.repo.Update(r.PathValue("id"), in.Title, in.Done)
if errors.Is(err, ErrNotFound) {
writeError(w, http.StatusNotFound, ErrNotFound.Error())
return
}
writeJSON(w, http.StatusOK, task)
}
func (a *App) deleteTask(w http.ResponseWriter, r *http.Request) {
if err := a.repo.Delete(r.PathValue("id")); errors.Is(err, ErrNotFound) {
writeError(w, http.StatusNotFound, ErrNotFound.Error())
return
}
w.WriteHeader(http.StatusNoContent)
}
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
// Cap request bodies and reject unknown fields before they reach repository code.
r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return errors.New("invalid JSON: " + err.Error())
}
if err := dec.Decode(&struct{}{}); err != io.EOF {
return errors.New("body must contain one JSON object")
}
return nil
}
func writeJSON(w http.ResponseWriter, status int, value any) {
// Headers must be set before WriteHeader; Encoder adds the trailing newline.
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
func main() {
log.SetFlags(0)
app := &App{repo: NewRepository()}
server := &http.Server{
Addr: ":8080",
Handler: app.routes(),
ReadHeaderTimeout: 5 * time.Second,
}
log.Println("task API listening on :8080")
log.Fatal(server.ListenAndServe())
}预期结果:保存为 main.go 后运行 go run main.go,进程会持续监听 8080 端口并输出:
task API listening on :8080如果 8080 已被占用,ListenAndServe 会返回 bind 错误;这不是路由问题,应先释放端口或把 Addr 改成其他端口,并同步修改下面的请求地址。
用请求验证 CRUD 与错误分支
保持服务运行,再执行下面一组请求。它依次覆盖创建、列表、更新、查询不存在、参数错误和删除;同一组命令可直接复制执行。
printf 'create\n'
curl -sS -w 'status=%{http_code}\n' -H 'Content-Type: application/json' -d '{"title":"ship API"}' http://localhost:8080/tasks
printf 'list\n'
curl -sS -w 'status=%{http_code}\n' http://localhost:8080/tasks
printf 'update\n'
curl -sS -w 'status=%{http_code}\n' -X PUT -H 'Content-Type: application/json' -d '{"title":"ship API","done":true}' http://localhost:8080/tasks/task-1
printf 'missing\n'
curl -sS -w 'status=%{http_code}\n' http://localhost:8080/tasks/task-999
printf 'bad-input\n'
curl -sS -w 'status=%{http_code}\n' -H 'Content-Type: application/json' -d '{"title":""}' http://localhost:8080/tasks
printf 'delete\n'
curl -sS -o /dev/null -w 'status=%{http_code}\n' -X DELETE http://localhost:8080/tasks/task-1预期输出:
create
{"id":"task-1","title":"ship API","done":false}
status=201
list
[{"id":"task-1","title":"ship API","done":false}]
status=200
update
{"id":"task-1","title":"ship API","done":true}
status=200
missing
{"error":"task not found"}
status=404
bad-input
{"error":"title is required"}
status=400
delete
status=204这里最重要的契约是:JSON 解析失败、空标题这类“请求本身不合法”返回 400;路径参数格式合法但对应任务不存在时返回 404。客户端因此不需要从错误字符串猜原因。
收紧 JSON 边界
http.MaxBytesReader(w, r.Body, 64<<10) 把单个请求限制为 65536 字节,避免异常大 body 占用过多内存;DisallowUnknownFields 会让 {"titel":"x"} 直接进入 400,而不是静默忽略拼错字段。对于这个小型任务 API,这两项成本很低,适合作为默认保护。
当前示例没有强制检查请求头 Content-Type,所以只要正文是合法 JSON 就能被解析。若发布契约明确要求 JSON,可以在 decodeJSON 前检查媒体类型,并对非 application/json 返回 415;不要把它混成 400,否则客户端无法区分“格式类型不支持”和“JSON 内容本身错误”。