如何实现服务器端超时?(对http.Server超时感到困惑) [英] How to implement server side timeouts? (Confused about http.Server timeouts)

查看:40
本文介绍了如何实现服务器端超时?(对http.Server超时感到困惑)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的服务实现服务器端超时.如果请求花费的时间超过X秒,则服务器应返回503 Service Unavailable.

I'm trying to implement server-side timeouts for my service. If the request takes longer than X seconds, the server should return 503 Service Unavailable.

我知道可以通过将所有端点包装在 http.TimeoutHandler中来轻松实现.,但是我很困惑为什么超时不会自动完成http.Server的字段

I know that this can easily be accomplished by wrapping all of my endpoints in http.TimeoutHandler, but I'm confused why this isn't being done automatically by the Timeout fields of http.Server

这是我用于测试的一个简单示例.如果我使用cURL或POSTman这个服务器,它将永远挂起,而不是我期望的5秒钟.

Here is a trivial example that I am using for testing. If I cURL or POSTman this server, it hangs forever, rather than the 5 seconds I expect.

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文章作为灵感. golang http超时的完整指南因此您想公开访问互联网

forgot to link some Cloudflare articles that I have been using as inspiration. complete guide to golang http timeouts so you want to expose go on the internet

推荐答案

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

The answer is to use http.TimeoutHandler. I misunderstood the purpose of the http.Server Timeout fields.

这篇关于如何实现服务器端超时?(对http.Server超时感到困惑)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆