HTTP 编程
# HTTP 编程
net/http 可以直接构建服务。服务端应配置超时,处理器从请求的 Context 获取取消信号。
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
})
server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
客户端应复用 http.Client 和 Transport、设置超时并关闭响应体。服务停止时使用 Shutdown(ctx) 完成优雅关闭,而不是直接终止正在处理的请求。