Skip to content

net/http: passing in nil *bytes.Reader to NewRequest panics #71407

@omusil24

Description

@omusil24

Go version

go version go1.23.4 darwin/arm64

Output of go env in your module/workspace:

.

What did you do?

Run a code similar to the following minimal example:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

func doRequest(reqBody interface{}) {
	var bodyReader *bytes.Reader
	if reqBody != nil {
		payloadBytes, err := json.Marshal(reqBody)
		if err != nil {
			return
		}
		bodyReader = bytes.NewReader(payloadBytes)
	}

	_, err := http.NewRequest("POST", "localhost:8080/abc", bodyReader)
	if err != nil {
		return
	}
	fmt.Println("ok")
}

func main() {
	// request body might be different values, here we just pass nil directly as an example
	doRequest(nil)
}

What did you see happen?

Running the code panics:

% go run main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x18 pc=0x10242bc10]

goroutine 1 [running]:
bytes.(*Reader).Len(...)
	/usr/local/go/src/bytes/reader.go:27
net/http.NewRequestWithContext({0x1024cf3e8, 0x1025f2540}, {0x10242dfa3?, 0x140000021c0?}, {0x10243091d?, 0x12?}, {0x1024ce508, 0x0})
	/usr/local/go/src/net/http/request.go:942 +0x400
net/http.NewRequest(...)
	/usr/local/go/src/net/http/request.go:872
main.doRequest({0x0?, 0x0?})
	/Users/user/test/main.go:20 +0xcc
main.main()
	/Users/user/test/main.go:28 +0x24
exit status 2

What did you expect to see?

The code should not panic and print "ok".

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions