Standard library / net/http

http.TimeoutHandler()

Wraps a handler with a duration limit and returns 503 when the handler does not finish in time. Cancellation is cooperative; not a way to forcibly stop arbitrary work. Expected stdout: '503\n'.

Formal Syntax & Structure

go syntaxgo
func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler

Parameters & Attributes

NameTypeDescription
hHandlerHandler to wrap or register.
dttime.DurationTime allowed for the wrapped handler.
msgstringResponse body for timed-out requests.

Return Value

Handler

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "bytes"  "fmt"  "io"  "mime/multipart"  "net"  "net/http"  "net/http/httptest"  "strings"  "time")
func main() {  h := http.TimeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }), 20*time.Millisecond, "timeout")  fmt.Println(rec(h, "GET", "/").Code)}func rec(h http.Handler, method, path string) *httptest.ResponseRecorder {  w := httptest.NewRecorder()  h.ServeHTTP(w, httptest.NewRequest(method, path, nil))  return w}func fixture() *httptest.Server {  return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }))}func localServer() (*http.Server, string, chan error) {  l := must(net.Listen("tcp4", "127.0.0.1:0"))  s := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }), ReadHeaderTimeout: time.Second}  done := make(chan error, 1)  go func() { done <- s.Serve(l) }()  return s, "http://" + l.Addr().String(), done}func form() *http.Request {  r := httptest.NewRequest("POST", "/?q=query", strings.NewReader("q=body&name=Go"))  r.Header.Set("Content-Type", "application/x-www-form-urlencoded")  return r}func multipartReq() *http.Request {  var b bytes.Buffer  w := multipart.NewWriter(&b)  f := must(w.CreateFormFile("upload", "demo.txt"))  _, e := io.WriteString(f, "hello")  check(e)  check(w.Close())  r := httptest.NewRequest("POST", "/", &b)  r.Header.Set("Content-Type", w.FormDataContentType())  return r}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference