From bf413d4fde785a93050d78998de2e38dbc854694 Mon Sep 17 00:00:00 2001
From: Will McCutchen <will@mccutch.org>
Date: Wed, 20 Jan 2021 15:23:03 -0500
Subject: [PATCH] Send 499 status when client cancels /delay

---
 httpbin/handlers.go      |  1 +
 httpbin/handlers_test.go | 14 ++++++++++++++
 2 files changed, 15 insertions(+)

diff --git a/httpbin/handlers.go b/httpbin/handlers.go
index 1343a02..5e95a9e 100644
--- a/httpbin/handlers.go
+++ b/httpbin/handlers.go
@@ -502,6 +502,7 @@ func (h *HTTPBin) Delay(w http.ResponseWriter, r *http.Request) {
 
 	select {
 	case <-r.Context().Done():
+		w.WriteHeader(499) // "Client Closed Request" https://httpstatuses.com/499
 		return
 	case <-time.After(delay):
 	}
diff --git a/httpbin/handlers_test.go b/httpbin/handlers_test.go
index e93f4f0..4371a3b 100644
--- a/httpbin/handlers_test.go
+++ b/httpbin/handlers_test.go
@@ -5,6 +5,7 @@ import (
 	"bytes"
 	"compress/gzip"
 	"compress/zlib"
+	"context"
 	"encoding/json"
 	"errors"
 	"fmt"
@@ -1469,6 +1470,19 @@ func TestDelay(t *testing.T) {
 		}
 	})
 
+	t.Run("cancelation causes 499", func(t *testing.T) {
+		ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+		defer cancel()
+
+		r, _ := http.NewRequestWithContext(ctx, "GET", "/delay/1s", nil)
+		w := httptest.NewRecorder()
+		handler.ServeHTTP(w, r)
+
+		if w.Code != 499 {
+			t.Errorf("expected 499 response, got %d", w.Code)
+		}
+	})
+
 	var badTests = []struct {
 		url  string
 		code int
-- 
GitLab