dongtan5558 2018-10-29 17:56
浏览 350
已采纳

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

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.

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

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()
}

EDIT: 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

  • 写回答

2条回答 默认 最新

  • dongqieli4164 2018-10-29 20:15
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容