Allow TimeoutHandler connections to be kept alive (#864)

This commit is contained in:
Erik Dubbelboer
2020-08-16 09:21:00 +02:00
committed by GitHub
parent a995d43d9c
commit 01acd76daf
2 changed files with 43 additions and 4 deletions
+1 -4
View File
@@ -2170,12 +2170,9 @@ func (s *Server) serveConn(c net.Conn) (err error) {
timeoutResponse = ctx.timeoutResponse
if timeoutResponse != nil {
// Acquire a new ctx because the old one will still be in use by the timeout out handler.
ctx = s.acquireCtx(c)
timeoutResponse.CopyTo(&ctx.Response)
if br != nil {
// Close connection, since br may be attached to the old ctx via ctx.fbr.
ctx.SetConnectionClose()
}
}
if !ctx.IsGet() && ctx.IsHead() {
+42
View File
@@ -2465,6 +2465,45 @@ func TestTimeoutHandlerTimeout(t *testing.T) {
}
}
func TestTimeoutHandlerTimeoutReuse(t *testing.T) {
t.Parallel()
ln := fasthttputil.NewInmemoryListener()
h := func(ctx *RequestCtx) {
if string(ctx.Path()) == "/timeout" {
time.Sleep(time.Second)
}
ctx.SetBodyString("ok")
}
s := &Server{
Handler: TimeoutHandler(h, 20*time.Millisecond, "timeout!!!"),
}
go func() {
if err := s.Serve(ln); err != nil {
t.Errorf("unexepcted error: %s", err)
}
}()
conn, err := ln.Dial()
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
br := bufio.NewReader(conn)
if _, err = conn.Write([]byte("GET /timeout HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
t.Fatalf("unexpected error: %s", err)
}
verifyResponse(t, br, StatusRequestTimeout, string(defaultContentType), "timeout!!!")
if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
t.Fatalf("unexpected error: %s", err)
}
verifyResponse(t, br, StatusOK, string(defaultContentType), "ok")
if err := ln.Close(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
}
func TestServerGetOnly(t *testing.T) {
t.Parallel()
@@ -2556,6 +2595,7 @@ func TestServerTimeoutErrorWithResponse(t *testing.T) {
br := bufio.NewReader(&rw.w)
verifyResponse(t, br, 456, "foo/bar", "path=/foo")
verifyResponse(t, br, 456, "foo/bar", "path=/bar")
data, err := ioutil.ReadAll(br)
if err != nil {
@@ -2599,6 +2639,7 @@ func TestServerTimeoutErrorWithCode(t *testing.T) {
br := bufio.NewReader(&rw.w)
verifyResponse(t, br, StatusBadRequest, string(defaultContentType), "stolen ctx")
verifyResponse(t, br, StatusBadRequest, string(defaultContentType), "stolen ctx")
data, err := ioutil.ReadAll(br)
if err != nil {
@@ -2642,6 +2683,7 @@ func TestServerTimeoutError(t *testing.T) {
br := bufio.NewReader(&rw.w)
verifyResponse(t, br, StatusRequestTimeout, string(defaultContentType), "stolen ctx")
verifyResponse(t, br, StatusRequestTimeout, string(defaultContentType), "stolen ctx")
data, err := ioutil.ReadAll(br)
if err != nil {