What you are seeing here is an edge case caused by the fact that the first 
NewRequest wraps your strings.Reader into a ioutil.NopCloser. When 
NewRequest is called the second time, the type switch no longer matches a 
type for which the length is known, so ContentLength is left to 0, which 
according to the docs means unknown. NewRequest implements this "best 
effort" method of determining the content length to avoid using the less 
efficient chunked encoding transfer method unless necessary, so you don't 
need to explicitly set the Content-Length header every time you create a 
new request.

That said, this is an artificial example which doesn't really reflect the 
way this API is used. If you were reverse proxying an incoming HTTP 
request, you would know the length of the body before reading it only if 
the client set a Content-Length header, which is optional. To properly 
proxy the request you would pass through the body reader, and copy the 
Content-Length header to the upstream request. You can check out the source 
code httputil.ReverseProxy 
<https://golang.org/pkg/net/http/httputil/#ReverseProxy> for a working 
implementation. An unset Request.ContentLength does not affect the ability 
to actually perform the request, although it might cause it to be sent with 
the somewhat less efficient chunked encoding method.

Hope this helps


On Tuesday, February 5, 2019 at 11:12:36 AM UTC-5, Matteo Biagetti wrote:
>
> I've the following situation: 
> I proxy a request to another server and when I made a POST and create a 
> new request, the contentLength is zero:
>
>         req2, _ := http.NewRequest(req.Method, newApiUrl , req.Body)
>         fmt.Println("New request from body:", req2.ContentLength) // print 
> 0
>
> Checking in the source code of the NewRequest func Body don't respect some 
> interface and populate the ContentLength field.
>
> Could be a bug? Which could be a valid approach in order to create a new 
> request from an existing one and correct set the Body length?
>
> A working example here:
>
> https://play.golang.org/p/SvCDLj0NrXb
>
> Thanks!
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to