如何实现服务器端超时?(对http.Server超时感到困惑)



我正在尝试为我的服务实现服务器端超时。如果请求花费的时间超过X秒,则服务器应返回503"服务不可用"。

我知道,通过将我的所有端点封装在http中,可以很容易地实现这一点。TimeoutHandler,但我很困惑为什么http的Timeout字段没有自动完成。服务器

下面是一个我正在用于测试的琐碎示例。如果我cURL或POSTman这个服务器,它将永远挂起,而不是我期望的5秒钟。

package main
import (
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/timeouttest", func(_ http.ResponseWriter, _ *http.Request) {
// busy infinite loop
// for { _ = struct {}{}}
// non-busy infinite loop
select {}
})
srv := &http.Server{
Addr:              "localhost:5000",
Handler:           mux,
ReadTimeout:       5 * time.Second,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout:      5 * time.Second,
IdleTimeout:       90 * time.Second,
}
srv.ListenAndServe()
}

编辑:忘记链接一些Cloudflare的文章,我一直在用这些文章作为灵感。golanghttp超时完整指南所以你想在互联网上曝光

答案是使用http.TimeoutHandler。我误解了http.Server超时字段的用途。

最新更新