// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package http provides helpers for HTTP servers. package http import ( "bytes" "errors" "io" "net/http" "sync" "time" ) // TimeoutHandler returns a Handler that runs h with the given time limit. // // The new Handler calls h.ServeHTTP to handle each request, but if a // call runs for longer than its time limit, the handler responds with // a 504 Gateway Timeout error and the given message in its body. // (If msg is empty, a suitable default message will be sent.) // After such a timeout, writes by h to its ResponseWriter will return // ErrHandlerTimeout. // // TimeoutHandler buffers all Handler writes to memory and does not // support the Hijacker or Flusher interfaces. func TimeoutHandler(h http.Handler, dt time.Duration, msg string) http.Handler { return &timeoutHandler{ handler: h, body: msg, dt: dt, } } // ErrHandlerTimeout is returned on ResponseWriter Write calls // in handlers which have timed out. var ErrHandlerTimeout = errors.New("http: Handler timeout") type timeoutHandler struct { handler http.Handler body string dt time.Duration // When set, no timer will be created and this channel will // be used instead. testTimeout <-chan time.Time } func (h *timeoutHandler) errorBody() string { if h.body != "" { return h.body } return "