Skip to content

Content-Length header missing for empty POST requests #996

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
N1cOs opened this issue Mar 30, 2025 · 4 comments
Closed

Content-Length header missing for empty POST requests #996

N1cOs opened this issue Mar 30, 2025 · 4 comments
Assignees

Comments

@N1cOs
Copy link

N1cOs commented Mar 30, 2025

Hello! Recently we faced with a problem, that resty Client doesn't set Content-Length header for an empty POST request.

Version - 2.16.5.

Example:

package main

import (
	"fmt"

	"github.com/go-resty/resty/v2"
)

func main() {
	client := resty.New()

	client.OnBeforeRequest(func(client *resty.Client, request *resty.Request) error {
		request.
			SetBody(nil).
			SetContentLength(true)

		return nil
	})

	client = client.SetBaseURL("http://localhost:8080")

	resp, err := client.R().Execute("POST", "/test")
	if err != nil {
		panic(err)
	}

	fmt.Println(resp)
}

Then I captured request with Wireshark and Content-Length header is missing:

Image
@N1cOs
Copy link
Author

N1cOs commented Mar 30, 2025

I did a little more research. It happens not only for POST requests but also for PUT, PATCH.

From version v2.16.2 there is a workaround to use http.NoBody explicitly.

@Libero-Dev
Copy link

@N1cOs I have created a PR for this. Ultimately I'm not so sure if this is something that should or shouldn't be merged in and supported as the omission of the Content-Length header seems to be something of an undocumented (that or documentation on this is very difficult to find) side effect in the standard http library when the resty request is built with http.NewRequest.

@N1cOs
Copy link
Author

N1cOs commented Apr 27, 2025

@Libero-Dev thanks for the fix. IMO it should be fix. Standard http library has the logic for handling a nil body. For instance, this code snippet writes Content-Length header in the request:

package main

import "net/http"

func main() {
	_, err := http.Post("http://localhost:8080/test", "application/json", nil)
	if err != nil {
		panic(err)
	}
}

Library sends the request:

POST /test HTTP/1.1
Host: localhost:8080
User-Agent: Go-http-client/1.1
Content-Length: 0
Content-Type: application/json
Accept-Encoding: gzip

@jeevatkm
Copy link
Member

This is fixed by PR #1003

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

3 participants