From 305126afcbcc662f2e97e6701a0bbe3cfdeaca56 Mon Sep 17 00:00:00 2001 From: ale <ale@incal.net> Date: Thu, 6 Feb 2020 10:52:24 +0000 Subject: [PATCH] Allow setting a timeout for request handling This is a high-level timeout for the http.Handler application code, not a low-level network timeout. --- serverutil/http.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/serverutil/http.go b/serverutil/http.go index 604ca98..f1c69b0 100644 --- a/serverutil/http.go +++ b/serverutil/http.go @@ -26,6 +26,7 @@ var gracefulShutdownTimeout = 3 * time.Second type ServerConfig struct { TLS *TLSServerConfig `yaml:"tls"` MaxInflightRequests int `yaml:"max_inflight_requests"` + RequestTimeoutSecs int `yaml:"request_timeout"` TrustedForwarders []string `yaml:"trusted_forwarders"` } @@ -60,11 +61,18 @@ func (config *ServerConfig) buildHTTPServer(h http.Handler) (*http.Server, error } } + // Wrap the handler with a TimeoutHandler if 'request_timeout' + // is set. + h = addDefaultHandlers(h) + if config.RequestTimeoutSecs > 0 { + h = http.TimeoutHandler(h, time.Duration(config.RequestTimeoutSecs)*time.Second, "") + } + // These are not meant to be external-facing servers, so we // can be generous with the timeouts to keep the number of // reconnections low. return &http.Server{ - Handler: defaultHandler(h), + Handler: h, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 600 * time.Second, @@ -134,7 +142,7 @@ func Serve(h http.Handler, config *ServerConfig, addr string) error { return nil } -func defaultHandler(h http.Handler) http.Handler { +func addDefaultHandlers(h http.Handler) http.Handler { root := http.NewServeMux() // Add an endpoint for HTTP health checking probes. -- GitLab