Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ const (
// withAppHeaders adds application headers such as X-App-Version and X-App-Name.
func withAppHeaders(c int, h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Consume the request body before responding. This allows clients to finish
// sending large payloads instead of having net/http close the connection
// with unread request data.
_, _ = io.Copy(io.Discard, r.Body)

w.Header().Set(httpHeaderAppName, version.Name)
w.Header().Set(httpHeaderAppVersion, version.Version)
w.WriteHeader(c)
Expand Down
51 changes: 51 additions & 0 deletions handlers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright IBM Corp. 2016, 2026
// SPDX-License-Identifier: MPL-2.0

package main

import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"testing"
)

func TestRequestBodyIsDrained(t *testing.T) {
for _, test := range []struct {
name string
size int
}{
{name: "small", size: 1 << 10},
{name: "20 MiB", size: 20 << 20},
} {
t.Run(test.name, func(t *testing.T) {
body := &countingReader{reader: bytes.NewReader(make([]byte, test.size))}
request := httptest.NewRequest(http.MethodPost, "/", io.NopCloser(body))
response := httptest.NewRecorder()

httpLog(io.Discard, withAppHeaders(http.StatusOK, httpEcho("hello")))(response, request)

if body.read != test.size {
t.Fatalf("read %d request-body bytes, want %d", body.read, test.size)
}
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", response.Code, http.StatusOK)
}
if got, want := response.Body.String(), "hello\n"; got != want {
t.Fatalf("body = %q, want %q", got, want)
}
})
}
}

type countingReader struct {
reader io.Reader
read int
}

func (r *countingReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
r.read += n
return n, err
}