Configure timeouts for `http.Server`
Go's `net/http` serve functions may be vulnerable to resource consumption attacks if timeouts are not properly configured prior to starting the HTTP server. An adversary may open up thousands of connections but never complete sending all data, or never terminate the connections. This may lead to the server no longer accepting new connections. To protect against this style of resource consumption attack, timeouts should be set in the `net/http` server prior to calling the listen or serve functions. What this means is that the default `http.ListenAndServe` and `http.Serve` functions should not be used in a production setting as they are unable to have timeouts configured. Instead a custom `http.Server` object must be created with the timeouts configured. Example setting timeouts on a `net/http` server: ``` // All values chosen below are dependent on application logic and // should be tailored per use-case srv := \u0026http.Server{ Addr: \"localhost:8000\", // ReadHeaderTimeout is the amount of time allowed to read // request headers. The connection's read deadline is reset // after reading the headers and the Handler can decide what // is considered too slow for the body. If ReadHeaderTimeout // is zero, the value of ReadTimeout is used. If both are // zero, there is no timeout. ReadHeaderTimeout: 15 * time.Second, // ReadTimeout is the maximum duration for reading the entire // request, including the body. A zero or negative value means // there will be no timeout. // // Because ReadTimeout does not let Handlers make per-request // decisions on each request body's acceptable deadline or // upload rate, most users will prefer to use // ReadHeaderTimeout. It is valid to use them both. ReadTimeout: 15 * time.Second, // WriteTimeout is the maximum duration before timing out // writes of the response. It is reset whenever a new // request's header is read. Like ReadTimeout, it does not // let Handlers make decisions on a per-request basis. // A zero or negative value means there will be no timeout. WriteTimeout: 10 * time.Second, // IdleTimeout is the maximum amount of time to wait for the // next request when keep-alives are enabled. If IdleTimeout // is zero, the value of ReadTimeout is used. If both are // zero, there is no timeout. IdleTimeout: 30 * time.Second, } // For per request timeouts applications can wrap all `http.HandlerFunc(...)` in // `http.TimeoutHandler`` and specify a timeout, but note the TimeoutHandler does not // start ticking until all headers have been read. // Listen with our custom server with timeouts configured if err := srv.ListenAndServe(); err != nil { log.Fatal(err) } ``` For more information on the `http.Server` timeouts, see: https://pkg.go.dev/net/http#Server For information on setting request based timeouts, see: https://pkg.go.dev/net/http#TimeoutHandler For more information on the Slowloris attack see: https://en.wikipedia.org/wiki/Slowloris_(computer_security)
issue