实战:任务登记 API
把 JSON 解析、并发保护、输入校验和 HTTP 状态码串成一个最小可运行服务。
行为与边界
POST /tasks 接收客户端给出的 id 和 title。同一个 ID 首次创建返回 201,重复提交返回 409。这个实现用内存 map 演示进程内并发,重启会丢数据。把下面代码保存为 main.go,运行 go run .。
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"strings"
"sync"
"time"
)
type task struct {
ID string `json:"id"`
Title string `json:"title"`
}
type tasks struct {
mu sync.Mutex
byID map[string]task
}
func (s *tasks) add(t task) bool {
s.mu.Lock()
defer s.mu.Unlock()
if _, exists := s.byID[t.ID]; exists {
return false
}
s.byID[t.ID] = t
return true
}
func (s *tasks) create(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 4096)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var t task
if err := dec.Decode(&t); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
if err := dec.Decode(new(any)); err != io.EOF {
http.Error(w, "expected one JSON value", http.StatusBadRequest)
return
}
t.ID = strings.TrimSpace(t.ID)
t.Title = strings.TrimSpace(t.Title)
if t.ID == "" || t.Title == "" {
http.Error(w, "id and title are required", http.StatusBadRequest)
return
}
if !s.add(t) {
http.Error(w, "duplicate id", http.StatusConflict)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(t); err != nil {
log.Print(err)
}
}
func main() {
store := &tasks{byID: make(map[string]task)}
mux := http.NewServeMux()
mux.HandleFunc("POST /tasks", store.create)
server := &http.Server{
Addr: "127.0.0.1:8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Fatal(server.ListenAndServe())
}
该路由语法需要 Go 1.22 或更新版本。用相同的请求连发两次,观察成功和重复的状态码。
curl -i http://127.0.0.1:8080/tasks \
-H 'Content-Type: application/json' \
-d '{"id":"go-01","title":"复习切片"}'
从练习走到实际项目
用 httptest 覆盖错误 JSON、缺字段、两个连续 JSON 值和重复 ID,再用 go test -race 检查并发写入。若改成多实例服务,状态可以存数据库,用唯一约束保护同一 ID。若要把重试定义成幂等,需要比较请求内容并返回同一次操作的状态。停机则用带期限的 Shutdown,处理挂起请求和后台工作。