net/http 可实现可维护 REST API:需封装 handler 返回 error、手动解析路径/查询参数、显式设 Content-Type 与状态码、用 TimeoutHandler 和 context 控制超时、httptest 写单元测试、配置 Server 级读写超时。

用 net/http 实现最简 REST API 路由
Go 标准库 net/http 足够支撑轻量级 REST API,无需框架也能清晰组织。关键不是“能不能”,而是路由是否可维护、错误是否可捕获、参数是否易提取。
常见错误是直接在 http.HandleFunc 里写业务逻辑,导致无法统一处理日志、超时、CORS 或 panic 恢复。正确做法是封装 handler 函数,显式接收 *http.Request 和 http.ResponseWriter,并返回 error 统一交由中间件处理。
- 路径参数需手动解析(如
/users/123中的123),http.ServeMux不支持占位符,要用strings.Split(r.URL.Path, "/")或正则匹配 - 查询参数用
r.URL.Query().Get("page"),注意空字符串和缺失键的区别 - 请求体必须显式调用
r.Body.Close(),否则连接不会复用,高并发下会耗尽文件描述符
用 json.Marshal 与 Content-Type 控制响应格式
REST API 的核心契约是状态码 + JSON body + 正确的 Content-Type。Go 默认不设 header,漏掉 w.Header().Set("Content-Type", "application/json; charset=utf-8") 会导致前端解析失败或乱码。
json.Marshal 对 nil slice、nil map、time.Time 默认输出空值或 panic(如未注册 time.Time 的 JSON marshaler)。生产环境务必预判字段类型:
立即学习“go语言免费学习笔记(深入)”;
type User struct {
ID int `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
}
func (u User) MarshalJSON() ([]byte, error) {
type Alias User // 防止无限递归
return json.Marshal(&struct {
*Alias
CreatedAt string `json:"created_at"`
}{
Alias: (*Alias)(&u),
CreatedAt: u.CreatedAt.Format(time.RFC3339),
})
}
- 不要用
fmt.Println打印响应体调试——它会干扰http.ResponseWriter的缓冲机制,可能触发 “http: response.WriteHeader called multiple times” - 400/404/500 等状态码必须显式调用
w.WriteHeader(http.StatusBadRequest),否则默认是 200 - 对空响应(如 DELETE 成功),仍要设
Content-Type并写空字节:w.Write(nil)
用 http.TimeoutHandler 处理超时而非依赖客户端
REST API 必须主动控制执行时间,尤其涉及数据库或外部 HTTP 调用时。Go 的 http.TimeoutHandler 是唯一标准方案,它包装已有 handler,在指定时间后中断响应并返回 503。
注意它只终止 handler 执行,不自动取消下游操作(如正在跑的 SQL 查询)。若需真正中断,得配合 context.Context 传入业务层:
handler := http.TimeoutHandler(http.HandlerFunc(userHandler), 5*time.Second, "timeout\n")
http.Handle("/users", handler)
func userHandler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
user, err := db.GetUser(ctx, userID) // 传入 ctx,让驱动可中断
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// ...
}
-
TimeoutHandler的 timeout 值应略大于业务层context.WithTimeout,避免双重超时干扰 - 不要在 handler 内部用
time.Sleep模拟延迟测试——它会阻塞 goroutine,而真实慢查询是 I/O 阻塞,行为不同 - 超时响应体默认是纯文本,如需 JSON,得自己实现 wrapper 或改用第三方中间件(如
gorilla/handlers)
用 go test + httptest 验证接口行为而非人工 curl
REST 接口一旦上线,修改路径、参数或状态码就是破坏性变更。单元测试必须覆盖:URL 路由是否命中、请求体能否解析、状态码是否符合预期、JSON 字段是否完整。
httptest.NewRecorder() 是关键,它模拟 http.ResponseWriter,让你断言 rec.Code、rec.Body.String() 和 header,无需启动真实服务:
func TestCreateUser(t *testing.T) {
req := httptest.NewRequest("POST", "/users", strings.NewReader(`{"name":"alice"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
createUserHandler(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("expected 201, got %d", w.Code)
}
var resp map[string]interface{}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if resp["id"] == nil {
t.Error("missing id field")
}
}
- 测试中不要用
http.ListenAndServe启服务——它阻塞主线程,且端口冲突难管理 - 对 400 错误,要测具体错误信息(如 JSON 解析失败时返回的 message),而不仅是状态码
- 测试路由时,用
http.ServeMux注册所有 handler 后再传给httptest.NewServer,可验证 mux 行为
http.Server.ReadTimeout 和 WriteTimeout。它们控制连接层面的读写超时,和 handler 超时互补——前者防慢速攻击(slowloris),后者防业务卡死。两者缺一不可。










