From a70a84787a073c90aa088244001fa7d091dfec6d Mon Sep 17 00:00:00 2001
From: Bill Mill <bill@billmill.org>
Date: Sun, 18 Jun 2023 11:00:12 -0400
Subject: [PATCH] fix: return empty data field for empty request bodies (#125)

When a request to `/anything` has an empty body, the `data` field of the
output should be the empty string. Currently, `go-httpbin is returning
`data:application/octet-stream;base64,`.

- Should the output actually be null? That would match `files`, `form`,
and `json`, but also would require deeper changes since `Data` is stored
as a string not a pointer, and I didn't want to mess with things any
more than I had to. An empty string works fine for my purposes
- how can I test this PR? I tried but I got confused by the TestAnything
method
- all the current tests pass under this change

This PR closes #124. Before:

```
$ curl -s 'http://0.0.0.0:8080/anything?one=two'
{
  "args": {
    "one": [
      "two"
    ]
  },
  "headers": {
    "Accept": [
      "*/*"
    ],
    "Host": [
      "0.0.0.0:8080"
    ],
    "User-Agent": [
      "curl/7.88.1"
    ]
  },
  "method": "GET",
  "origin": "127.0.0.1:60402",
  "url": "http://0.0.0.0:8080/anything?one=two",
  "data": "data:application/octet-stream;base64,",
  "files": null,
  "form": null,
  "json": null
}
```

After:
```
$ curl -s 'http://0.0.0.0:8080/anything?one=two'
{
  "args": {
    "one": [
      "two"
    ]
  },
  "headers": {
    "Accept": [
      "*/*"
    ],
    "Host": [
      "0.0.0.0:8080"
    ],
    "User-Agent": [
      "curl/7.88.1"
    ]
  },
  "method": "GET",
  "origin": "127.0.0.1:60595",
  "url": "http://0.0.0.0:8080/anything?one=two",
  "data": "",
  "files": null,
  "form": null,
  "json": null
}
```
---
 httpbin/helpers.go | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/httpbin/helpers.go b/httpbin/helpers.go
index 2e75e74..726d150 100644
--- a/httpbin/helpers.go
+++ b/httpbin/helpers.go
@@ -126,6 +126,11 @@ func parseBody(w http.ResponseWriter, r *http.Request, resp *bodyResponse) error
 	}
 	resp.Data = string(body)
 
+	// if we read an empty body, there's no need to do anything further
+	if len(resp.Data) == 0 {
+		return nil
+	}
+
 	// After reading the body to populate resp.Data, we need to re-wrap it in
 	// an io.Reader for further processing below
 	r.Body.Close()
-- 
GitLab