From cbbc2968cf3253a36052369af68080be5986d196 Mon Sep 17 00:00:00 2001
From: Will McCutchen <will@mccutch.org>
Date: Mon, 13 Mar 2023 10:33:29 -0400
Subject: [PATCH] fix: properly handle /bytes/0 (#115)

Fixes #112.

BREAKING CHANGE: Requests for zero bytes now actually return zero bytes.
Requests for negative numbers of bytes are now rejected.
---
 httpbin/handlers.go      | 17 ++++++++++++++---
 httpbin/handlers_test.go |  5 ++++-
 2 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/httpbin/handlers.go b/httpbin/handlers.go
index be4a018..536d271 100644
--- a/httpbin/handlers.go
+++ b/httpbin/handlers.go
@@ -785,9 +785,20 @@ func handleBytes(w http.ResponseWriter, r *http.Request, streaming bool) {
 		return
 	}
 
-	if numBytes < 1 {
-		numBytes = 1
-	} else if numBytes > 100*1024 {
+	if numBytes < 0 {
+		http.Error(w, "Bad Request", http.StatusBadRequest)
+		return
+	}
+
+	// Special case 0 bytes and exit early, since streaming & chunk size do not
+	// matter here.
+	if numBytes == 0 {
+		w.Header().Set("Content-Length", "0")
+		w.WriteHeader(http.StatusOK)
+		return
+	}
+
+	if numBytes > 100*1024 {
 		numBytes = 100 * 1024
 	}
 
diff --git a/httpbin/handlers_test.go b/httpbin/handlers_test.go
index f85c42f..397a151 100644
--- a/httpbin/handlers_test.go
+++ b/httpbin/handlers_test.go
@@ -2455,7 +2455,8 @@ func TestBytes(t *testing.T) {
 		url                   string
 		expectedContentLength int
 	}{
-		{"/bytes/-1", 1},
+		{"/bytes/0", 0},
+		{"/bytes/1", 1},
 		{"/bytes/99999999", 100 * 1024},
 
 		// negative seed allowed
@@ -2480,6 +2481,8 @@ func TestBytes(t *testing.T) {
 		url            string
 		expectedStatus int
 	}{
+		{"/bytes/-1", http.StatusBadRequest},
+
 		{"/bytes", http.StatusNotFound},
 		{"/bytes/16/foo", http.StatusNotFound},
 
-- 
GitLab