Skip to content

net/http: http2 with header connection:close causes the failure of rewinding body after connection loss #62450

Closed
@leizongmin

Description

@leizongmin

What version of Go are you using (go version)?

$ go version
go version go1.20.4 darwin/amd64

Does this issue reproduce with the latest release?

Run the following code:

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"net/http"
	"sync"
)

func main() {
	// condition 1: request a http2 server
	const u = "https://http2.github.io/"
	const n = 30

	wg := sync.WaitGroup{}
	wg.Add(n)
	counter := 0

	makeRequest := func(u string) (*http.Response, error) {
		// condition 2: body is not nil
		body := io.NopCloser(bytes.NewBuffer([]byte("hello")))
		req, err := http.NewRequest("POST", u, body)
		if err != nil {
			return nil, err
		}

		// condition 3: add header `connection: close`
		req.Header.Set("connection", "close")

		res, err := http.DefaultClient.Do(req)
		return res, err
	}

	// condition 4: concurrent multiple requests
	for i := 0; i < n; i++ {
		go func(i int) {
			defer wg.Done()
			res, err := makeRequest(fmt.Sprintf("%s?i=%d", u, i))
			if err != nil {
				log.Println(err)
				counter++
				return
			}
			defer res.Body.Close()
		}(i)
	}

	wg.Wait()
	log.Println("total", n, "error", counter)
}

What operating system and processor architecture are you using (go env)?

go env Output
$ go env

What did you do?

What did you expect to see?

2023/09/05 16:52:40 total 30 error 0

What did you see instead?

2023/09/05 16:52:40 Post "https://http2.github.io/?i=29": net/http: cannot rewind body after connection loss
2023/09/05 16:52:40 Post "https://http2.github.io/?i=8": net/http: cannot rewind body after connection loss
2023/09/05 16:52:40 Post "https://http2.github.io/?i=16": net/http: cannot rewind body after connection loss
2023/09/05 16:52:40 Post "https://http2.github.io/?i=10": net/http: cannot rewind body after connection loss
2023/09/05 16:52:40 Post "https://http2.github.io/?i=5": net/http: cannot rewind body after connection loss
2023/09/05 16:52:40 Post "https://http2.github.io/?i=20": net/http: cannot rewind body after connection loss
2023/09/05 16:52:40 total 30 error 6

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions