Go / 系统课时
返回状态码与 JSON 错误
返回状态码与 JSON 错误
接口失败时,客户端需要同时拿到正确的 HTTP 状态码和稳定的 JSON 结构。本篇用一个可运行的 net/http 服务统一设置 Content-Type、状态码和错误体,并演示为什么响应头必须在写入正文之前确定。
学习目标
- 用固定 helper 返回 JSON,并明确控制
Content-Type与状态码 - 设计统一错误结构,让 400、404、405 等响应保持同一格式
- 识别隐式 200 和重复
WriteHeader两类常见错误
用一个出口写状态码和 JSON
net/http 在第一次调用 Write 时,如果还没有显式调用 WriteHeader,会自动发送 200 OK。因此 JSON helper 的顺序应固定为:先设置响应头,再调用 WriteHeader(status),最后写入正文。错误响应也应复用同一个 helper,避免每个 Handler 各写一套格式。
下面的程序提供 /users/{id}。只接受 GET;空 ID 返回 400,未知 ID 返回 404,其他方法返回 405。错误体统一为 {"error":{"code":"...","message":"..."}}。
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
)
type APIError struct {
Error ErrorDetail `json:"error"`
}
type ErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
}
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
// 状态码已经发出;编码失败时只能记录,不能再改成另一个状态码。
if err := json.NewEncoder(w).Encode(value); err != nil {
log.Printf("encode response: %v", err)
}
}
func writeError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, APIError{
Error: ErrorDetail{
Code: code,
Message: message,
},
})
}
func userHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet)
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only GET is allowed")
return
}
id := strings.TrimPrefix(r.URL.Path, "/users/")
if id == "" || id == r.URL.Path {
writeError(w, http.StatusBadRequest, "bad_request", "user id is required")
return
}
if id != "42" {
writeError(w, http.StatusNotFound, "not_found", "user not found")
return
}
writeJSON(w, http.StatusOK, User{ID: "42", Name: "Ada"})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/users/", userHandler)
log.Println("listening on :8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}预期结果:保存为 main.go 后可直接编译运行;所有成功与失败响应都会声明 application/json; charset=utf-8,且错误字段始终位于顶层 error 对象中。
运行并检查 HTTP 响应
先启动服务:
go run main.go预期输出:
<TIME> listening on :8080实际日志时间会因运行环境不同而变化。
另开终端请求一个不存在的用户:
curl -i http://localhost:8080/users/99预期输出:
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: <TIME>
Content-Length: 58
{"error":{"code":"not_found","message":"user not found"}}Date 由服务器运行时决定,实际值可能不同。关键验收点是状态行为 404、JSON Content-Type 以及稳定的错误字段。
避免隐式 200 和重复写头
错误写法通常是先写正文再补状态码,例如先调用 json.NewEncoder(w).Encode(...),随后才调用 w.WriteHeader(http.StatusBadRequest)。第一次写正文时 200 已经发送,后续 WriteHeader 不会把客户端看到的状态改成 400。
同一个响应也只应选择一次最终状态。WriteHeader 调用后再调用第二次不会重写已发送的响应头,还可能产生 http: superfluous response.WriteHeader call 日志。实际项目中可把 writeJSON 和 writeError 放到独立包里,所有 Handler 只传入状态码和业务数据,避免漏设头部或重复写响应。