MCPcopy Create free account
hub / github.com/imroc/req / probeRequestBody

Method probeRequestBody

transfer.go:179–219  ·  view source on GitHub ↗

probeRequestBody reads a byte from t.Body to see whether it's empty (returns io.EOF right away). But because we've had problems with this blocking users in the past (issue 17480) when the body is a pipe (perhaps waiting on the response headers before the pipe is fed data), we need to be careful and

()

Source from the content-addressed store, hash-verified

177// In other words, this delay will not normally affect anybody, and there
178// are workarounds if it does.
179func (t *transferWriter) probeRequestBody() {
180 t.ByteReadCh = make(chan readResult, 1)
181 go func(body io.Reader) {
182 var buf [1]byte
183 var rres readResult
184 rres.n, rres.err = body.Read(buf[:])
185 if rres.n == 1 {
186 rres.b = buf[0]
187 }
188 t.ByteReadCh <- rres
189 close(t.ByteReadCh)
190 }(t.Body)
191 timer := time.NewTimer(200 * time.Millisecond)
192 select {
193 case rres := <-t.ByteReadCh:
194 timer.Stop()
195 if rres.n == 0 && rres.err == io.EOF {
196 // It was empty.
197 t.Body = nil
198 t.ContentLength = 0
199 } else if rres.n == 1 {
200 if rres.err != nil {
201 t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
202 } else {
203 t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
204 }
205 } else if rres.err != nil {
206 t.Body = errorReader{rres.err}
207 }
208 case <-timer.C:
209 // Too slow. Don't wait. Read it later, and keep
210 // assuming that this is ContentLength == -1
211 // (unknown), which means we'll send a
212 // "Transfer-Encoding: chunked" header.
213 t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
214 // Request that Request.Write flush the headers to the
215 // network before writing the body, since our body may not
216 // become readable until it's seen the response headers.
217 t.FlushHeaders = true
218 }
219}
220
221func noResponseBodyExpected(requestMethod string) bool {
222 return requestMethod == "HEAD"

Callers 1

Calls 2

StopMethod · 0.80
ReadMethod · 0.45

Tested by

no test coverage detected