Skip to content

net/http: client do not set Content-Length: 0 with an io.Reader with no bytes. #20257

Closed
@SunRunAway

Description

@SunRunAway

Please answer these questions before submitting your issue. Thanks!

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

go version go1.8.1 darwin/amd64

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

darwin/amd64

What did you do?

I called http.NewRequest and explicitly set req.ContentLength to 0.

package main

import (
	"io"
	"log"
	"net/http"
	"os"
)

type nilbody struct{}

func (nilbody) Read(p []byte) (int, error) {
	return 0, io.EOF
}

func main() {
	body := nilbody{}
	req, err := http.NewRequest("POST", "http://httpbin.org/post", body)
	if err != nil {
		log.Fatal(err)
	}
	req.ContentLength = 0
	resp, _ := http.DefaultClient.Do(req)
	io.Copy(os.Stdout, resp.Body)
}

What did you expect to see?

server should get a header with Content-Length: 0

What did you see instead?

With go1.8.1, server get a chunked request body, but older version get a explicit Content-Length header.

[sunrunaway:/tmp]$ go run nilbody.go
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "Transfer-Encoding": "chunked", 
    "User-Agent": "Go-http-client/1.1"
  }, 
  "json": null, 
  "origin": "180.168.57.238", 
  "url": "http://httpbin.org/post"
}
[sunrunaway:/tmp]$ /usr/local/Cellar/go/1.7.3/bin/go run nilbody.go 
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Connection": "close", 
    "Content-Length": "0", 
    "Host": "httpbin.org", 
    "User-Agent": "Go-http-client/1.1"
  }, 
  "json": null, 
  "origin": "180.168.57.238", 
  "url": "http://httpbin.org/post"
}

I know this is documented that 'a value of 0 means unknown if Body is not nil', but could it be possible to do some fix and not break our old code.

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