net/http/cgi: don't pass nil Body to the child handler

For server requests, the http.Request Body should not be nil.

Fixes #39190

Change-Id: I32de7b6c0f6ca55008fea9fd86089cda0a2dea62
Reviewed-on: https://go-review.googlesource.com/c/go/+/235137
Reviewed-by: Bryan C. Mills <bcmills@google.com>
Run-TryBot: Bryan C. Mills <bcmills@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/src/net/http/cgi/child.go b/src/net/http/cgi/child.go
index 9474175..d7d813e 100644
--- a/src/net/http/cgi/child.go
+++ b/src/net/http/cgi/child.go
@@ -146,6 +146,9 @@
 	if err != nil {
 		return err
 	}
+	if req.Body == nil {
+		req.Body = http.NoBody
+	}
 	if handler == nil {
 		handler = http.DefaultServeMux
 	}
diff --git a/src/net/http/cgi/integration_test.go b/src/net/http/cgi/integration_test.go
index 32d59c0..eaa090f 100644
--- a/src/net/http/cgi/integration_test.go
+++ b/src/net/http/cgi/integration_test.go
@@ -152,6 +152,23 @@
 	}
 }
 
+// Test that a child handler does not receive a nil Request Body.
+// golang.org/issue/39190
+func TestNilRequestBody(t *testing.T) {
+	testenv.MustHaveExec(t)
+
+	h := &Handler{
+		Path: os.Args[0],
+		Root: "/test.go",
+		Args: []string{"-test.run=TestBeChildCGIProcess"},
+	}
+	expectedMap := map[string]string{
+		"nil-request-body": "false",
+	}
+	_ = runCgiTest(t, h, "POST /test.go?nil-request-body=1 HTTP/1.0\nHost: example.com\n\n", expectedMap)
+	_ = runCgiTest(t, h, "POST /test.go?nil-request-body=1 HTTP/1.0\nHost: example.com\nContent-Length: 0\n\n", expectedMap)
+}
+
 // golang.org/issue/7198
 func Test500WithNoHeaders(t *testing.T)     { want500Test(t, "/immediate-disconnect") }
 func Test500WithNoContentType(t *testing.T) { want500Test(t, "/no-content-type") }
@@ -198,6 +215,10 @@
 		os.Exit(0)
 	}
 	Serve(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
+		if req.FormValue("nil-request-body") == "1" {
+			fmt.Fprintf(rw, "nil-request-body=%v\n", req.Body == nil)
+			return
+		}
 		rw.Header().Set("X-Test-Header", "X-Test-Value")
 		req.ParseForm()
 		if req.FormValue("no-body") == "1" {