1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
23 "golang_org/x/net/http/httpguts"
26 // ErrLineTooLong is returned when reading request or response bodies
27 // with malformed chunked encoding.
28 var ErrLineTooLong = internal.ErrLineTooLong
30 type errorReader struct {
34 func (r errorReader) Read(p []byte) (n int, err error) {
38 type byteReader struct {
43 func (br *byteReader) Read(p []byte) (n int, err error) {
55 // transferBodyReader is an io.Reader that reads from tw.Body
56 // and records any non-EOF error in tw.bodyReadError.
57 // It is exactly 1 pointer wide to avoid allocations into interfaces.
58 type transferBodyReader struct{ tw *transferWriter }
60 func (br transferBodyReader) Read(p []byte) (n int, err error) {
61 n, err = br.tw.Body.Read(p)
62 if err != nil && err != io.EOF {
63 br.tw.bodyReadError = err
68 // transferWriter inspects the fields of a user-supplied Request or Response,
69 // sanitizes them without changing the user object and provides methods for
70 // writing the respective header, body and trailer in wire format.
71 type transferWriter struct {
76 ContentLength int64 // -1 means unknown, 0 means exactly none
78 TransferEncoding []string
82 bodyReadError error // any non-EOF error from reading Body
84 FlushHeaders bool // flush headers to network before body
85 ByteReadCh chan readResult // non-nil if probeRequestBody called
88 func newTransferWriter(r interface{}) (t *transferWriter, err error) {
91 // Extract relevant fields
92 atLeastHTTP11 := false
93 switch rr := r.(type) {
95 if rr.ContentLength != 0 && rr.Body == nil {
96 return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
98 t.Method = valueOrDefault(rr.Method, "GET")
100 t.TransferEncoding = rr.TransferEncoding
102 t.Trailer = rr.Trailer
104 t.BodyCloser = rr.Body
105 t.ContentLength = rr.outgoingLength()
106 if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
107 t.TransferEncoding = []string{"chunked"}
109 // If there's a body, conservatively flush the headers
110 // to any bufio.Writer we're writing to, just in case
111 // the server needs the headers early, before we copy
112 // the body and possibly block. We make an exception
113 // for the common standard library in-memory types,
114 // though, to avoid unnecessary TCP packets on the
115 // wire. (Issue 22088.)
116 if t.ContentLength != 0 && !isKnownInMemoryReader(t.Body) {
117 t.FlushHeaders = true
120 atLeastHTTP11 = true // Transport requests are always 1.1 or 2.0
123 if rr.Request != nil {
124 t.Method = rr.Request.Method
127 t.BodyCloser = rr.Body
128 t.ContentLength = rr.ContentLength
130 t.TransferEncoding = rr.TransferEncoding
132 t.Trailer = rr.Trailer
133 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
134 t.ResponseToHEAD = noResponseBodyExpected(t.Method)
137 // Sanitize Body,ContentLength,TransferEncoding
138 if t.ResponseToHEAD {
140 if chunked(t.TransferEncoding) {
144 if !atLeastHTTP11 || t.Body == nil {
145 t.TransferEncoding = nil
147 if chunked(t.TransferEncoding) {
149 } else if t.Body == nil { // no chunking, no body
155 if !chunked(t.TransferEncoding) {
162 // shouldSendChunkedRequestBody reports whether we should try to send a
163 // chunked request body to the server. In particular, the case we really
164 // want to prevent is sending a GET or other typically-bodyless request to a
165 // server with a chunked body when the body has zero bytes, since GETs with
166 // bodies (while acceptable according to specs), even zero-byte chunked
167 // bodies, are approximately never seen in the wild and confuse most
168 // servers. See Issue 18257, as one example.
170 // The only reason we'd send such a request is if the user set the Body to a
171 // non-nil value (say, ioutil.NopCloser(bytes.NewReader(nil))) and didn't
172 // set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
173 // there's bytes to send.
175 // This code tries to read a byte from the Request.Body in such cases to see
176 // whether the body actually has content (super rare) or is actually just
177 // a non-nil content-less ReadCloser (the more common case). In that more
178 // common case, we act as if their Body were nil instead, and don't send
180 func (t *transferWriter) shouldSendChunkedRequestBody() bool {
181 // Note that t.ContentLength is the corrected content length
182 // from rr.outgoingLength, so 0 actually means zero, not unknown.
183 if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
186 if requestMethodUsuallyLacksBody(t.Method) {
187 // Only probe the Request.Body for GET/HEAD/DELETE/etc
188 // requests, because it's only those types of requests
189 // that confuse servers.
190 t.probeRequestBody() // adjusts t.Body, t.ContentLength
193 // For all other request types (PUT, POST, PATCH, or anything
194 // made-up we've never heard of), assume it's normal and the server
195 // can deal with a chunked request body. Maybe we'll adjust this
200 // probeRequestBody reads a byte from t.Body to see whether it's empty
201 // (returns io.EOF right away).
203 // But because we've had problems with this blocking users in the past
204 // (issue 17480) when the body is a pipe (perhaps waiting on the response
205 // headers before the pipe is fed data), we need to be careful and bound how
206 // long we wait for it. This delay will only affect users if all the following
208 // * the request body blocks
209 // * the content length is not set (or set to -1)
210 // * the method doesn't usually have a body (GET, HEAD, DELETE, ...)
211 // * there is no transfer-encoding=chunked already set.
212 // In other words, this delay will not normally affect anybody, and there
213 // are workarounds if it does.
214 func (t *transferWriter) probeRequestBody() {
215 t.ByteReadCh = make(chan readResult, 1)
216 go func(body io.Reader) {
219 rres.n, rres.err = body.Read(buf[:])
225 timer := time.NewTimer(200 * time.Millisecond)
227 case rres := <-t.ByteReadCh:
229 if rres.n == 0 && rres.err == io.EOF {
233 } else if rres.n == 1 {
235 t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
237 t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
239 } else if rres.err != nil {
240 t.Body = errorReader{rres.err}
243 // Too slow. Don't wait. Read it later, and keep
244 // assuming that this is ContentLength == -1
245 // (unknown), which means we'll send a
246 // "Transfer-Encoding: chunked" header.
247 t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
248 // Request that Request.Write flush the headers to the
249 // network before writing the body, since our body may not
250 // become readable until it's seen the response headers.
251 t.FlushHeaders = true
255 func noResponseBodyExpected(requestMethod string) bool {
256 return requestMethod == "HEAD"
259 func (t *transferWriter) shouldSendContentLength() bool {
260 if chunked(t.TransferEncoding) {
263 if t.ContentLength > 0 {
266 if t.ContentLength < 0 {
269 // Many servers expect a Content-Length for these methods
270 if t.Method == "POST" || t.Method == "PUT" {
273 if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
274 if t.Method == "GET" || t.Method == "HEAD" {
283 func (t *transferWriter) WriteHeader(w io.Writer) error {
284 if t.Close && !hasToken(t.Header.get("Connection"), "close") {
285 if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
290 // Write Content-Length and/or Transfer-Encoding whose values are a
291 // function of the sanitized field triple (Body, ContentLength,
293 if t.shouldSendContentLength() {
294 if _, err := io.WriteString(w, "Content-Length: "); err != nil {
297 if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
300 } else if chunked(t.TransferEncoding) {
301 if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
306 // Write Trailer header
307 if t.Trailer != nil {
308 keys := make([]string, 0, len(t.Trailer))
309 for k := range t.Trailer {
310 k = CanonicalHeaderKey(k)
312 case "Transfer-Encoding", "Trailer", "Content-Length":
313 return &badStringError{"invalid Trailer key", k}
315 keys = append(keys, k)
319 // TODO: could do better allocation-wise here, but trailers are rare,
320 // so being lazy for now.
321 if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
330 func (t *transferWriter) WriteBody(w io.Writer) error {
336 var body = transferBodyReader{t}
337 if chunked(t.TransferEncoding) {
338 if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
339 w = &internal.FlushAfterChunkWriter{Writer: bw}
341 cw := internal.NewChunkedWriter(w)
342 _, err = io.Copy(cw, body)
346 } else if t.ContentLength == -1 {
347 ncopy, err = io.Copy(w, body)
349 ncopy, err = io.Copy(w, io.LimitReader(body, t.ContentLength))
354 nextra, err = io.Copy(ioutil.Discard, body)
361 if t.BodyCloser != nil {
362 if err := t.BodyCloser.Close(); err != nil {
367 if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
368 return fmt.Errorf("http: ContentLength=%d with Body length %d",
369 t.ContentLength, ncopy)
372 if chunked(t.TransferEncoding) {
373 // Write Trailer header
374 if t.Trailer != nil {
375 if err := t.Trailer.Write(w); err != nil {
379 // Last chunk, empty trailer
380 _, err = io.WriteString(w, "\r\n")
385 type transferReader struct {
395 TransferEncoding []string
400 func (t *transferReader) protoAtLeast(m, n int) bool {
401 return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
404 // bodyAllowedForStatus reports whether a given response status code
405 // permits a body. See RFC 7230, section 3.3.
406 func bodyAllowedForStatus(status int) bool {
408 case status >= 100 && status <= 199:
419 suppressedHeaders304 = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
420 suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
423 func suppressedHeaders(status int) []string {
426 // RFC 7232 section 4.1
427 return suppressedHeaders304
428 case !bodyAllowedForStatus(status):
429 return suppressedHeadersNoBody
434 // msg is *Request or *Response.
435 func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
436 t := &transferReader{RequestMethod: "GET"}
440 switch rr := msg.(type) {
443 t.StatusCode = rr.StatusCode
444 t.ProtoMajor = rr.ProtoMajor
445 t.ProtoMinor = rr.ProtoMinor
446 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
448 if rr.Request != nil {
449 t.RequestMethod = rr.Request.Method
453 t.RequestMethod = rr.Method
454 t.ProtoMajor = rr.ProtoMajor
455 t.ProtoMinor = rr.ProtoMinor
456 // Transfer semantics for Requests are exactly like those for
457 // Responses with status code 200, responding to a GET method
461 panic("unexpected type")
464 // Default to HTTP/1.1
465 if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
466 t.ProtoMajor, t.ProtoMinor = 1, 1
469 // Transfer encoding, content length
470 err = t.fixTransferEncoding()
475 realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
479 if isResponse && t.RequestMethod == "HEAD" {
480 if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
486 t.ContentLength = realLength
490 t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
495 // If there is no Content-Length or chunked Transfer-Encoding on a *Response
496 // and the status is not 1xx, 204 or 304, then the body is unbounded.
497 // See RFC 7230, section 3.3.
500 if realLength == -1 &&
501 !chunked(t.TransferEncoding) &&
502 bodyAllowedForStatus(t.StatusCode) {
508 // Prepare body reader. ContentLength < 0 means chunked encoding
509 // or close connection when finished, since multipart is not supported yet
511 case chunked(t.TransferEncoding):
512 if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
515 t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
517 case realLength == 0:
520 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
522 // realLength < 0, i.e. "Content-Length" not mentioned in header
524 // Close semantics (i.e. HTTP/1.0)
525 t.Body = &body{src: r, closing: t.Close}
527 // Persistent connection (i.e. HTTP/1.1)
533 switch rr := msg.(type) {
536 rr.ContentLength = t.ContentLength
537 rr.TransferEncoding = t.TransferEncoding
539 rr.Trailer = t.Trailer
542 rr.ContentLength = t.ContentLength
543 rr.TransferEncoding = t.TransferEncoding
545 rr.Trailer = t.Trailer
551 // Checks whether chunked is part of the encodings stack
552 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
554 // Checks whether the encoding is explicitly "identity".
555 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
557 // fixTransferEncoding sanitizes t.TransferEncoding, if needed.
558 func (t *transferReader) fixTransferEncoding() error {
559 raw, present := t.Header["Transfer-Encoding"]
563 delete(t.Header, "Transfer-Encoding")
565 // Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
566 if !t.protoAtLeast(1, 1) {
570 encodings := strings.Split(raw[0], ",")
571 te := make([]string, 0, len(encodings))
572 // TODO: Even though we only support "identity" and "chunked"
573 // encodings, the loop below is designed with foresight. One
574 // invariant that must be maintained is that, if present,
575 // chunked encoding must always come first.
576 for _, encoding := range encodings {
577 encoding = strings.ToLower(strings.TrimSpace(encoding))
578 // "identity" encoding is not recorded
579 if encoding == "identity" {
582 if encoding != "chunked" {
583 return &badStringError{"unsupported transfer encoding", encoding}
585 te = te[0 : len(te)+1]
586 te[len(te)-1] = encoding
589 return &badStringError{"too many transfer encodings", strings.Join(te, ",")}
592 // RFC 7230 3.3.2 says "A sender MUST NOT send a
593 // Content-Length header field in any message that
594 // contains a Transfer-Encoding header field."
597 // "If a message is received with both a
598 // Transfer-Encoding and a Content-Length header
599 // field, the Transfer-Encoding overrides the
600 // Content-Length. Such a message might indicate an
601 // attempt to perform request smuggling (Section 9.5)
602 // or response splitting (Section 9.4) and ought to be
603 // handled as an error. A sender MUST remove the
604 // received Content-Length field prior to forwarding
605 // such a message downstream."
607 // Reportedly, these appear in the wild.
608 delete(t.Header, "Content-Length")
609 t.TransferEncoding = te
616 // Determine the expected body length, using RFC 7230 Section 3.3. This
617 // function is not a method, because ultimately it should be shared by
618 // ReadResponse and ReadRequest.
619 func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
620 isRequest := !isResponse
621 contentLens := header["Content-Length"]
623 // Hardening against HTTP request smuggling
624 if len(contentLens) > 1 {
625 // Per RFC 7230 Section 3.3.2, prevent multiple
626 // Content-Length headers if they differ in value.
627 // If there are dups of the value, remove the dups.
629 first := strings.TrimSpace(contentLens[0])
630 for _, ct := range contentLens[1:] {
631 if first != strings.TrimSpace(ct) {
632 return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
636 // deduplicate Content-Length
637 header.Del("Content-Length")
638 header.Add("Content-Length", first)
640 contentLens = header["Content-Length"]
643 // Logic based on response type or status
644 if noResponseBodyExpected(requestMethod) {
645 // For HTTP requests, as part of hardening against request
646 // smuggling (RFC 7230), don't allow a Content-Length header for
647 // methods which don't permit bodies. As an exception, allow
648 // exactly one Content-Length header if its value is "0".
649 if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
650 return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
662 // Logic based on Transfer-Encoding
667 // Logic based on Content-Length
669 if len(contentLens) == 1 {
670 cl = strings.TrimSpace(contentLens[0])
673 n, err := parseContentLength(cl)
679 header.Del("Content-Length")
682 // RFC 7230 neither explicitly permits nor forbids an
683 // entity-body on a GET request so we permit one if
684 // declared, but we default to 0 here (not -1 below)
685 // if there's no mention of a body.
686 // Likewise, all other request methods are assumed to have
687 // no body if neither Transfer-Encoding chunked nor a
688 // Content-Length are set.
692 // Body-EOF logic based on other methods (like closing, or chunked coding)
696 // Determine whether to hang up after sending a request and body, or
697 // receiving a response and body
698 // 'header' is the request headers
699 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
704 conv := header["Connection"]
705 hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
706 if major == 1 && minor == 0 {
707 return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
710 if hasClose && removeCloseHeader {
711 header.Del("Connection")
717 // Parse the trailer header
718 func fixTrailer(header Header, te []string) (Header, error) {
719 vv, ok := header["Trailer"]
723 header.Del("Trailer")
725 trailer := make(Header)
727 for _, v := range vv {
728 foreachHeaderElement(v, func(key string) {
729 key = CanonicalHeaderKey(key)
731 case "Transfer-Encoding", "Trailer", "Content-Length":
733 err = &badStringError{"bad trailer key", key}
743 if len(trailer) == 0 {
747 // Trailer and no chunking
748 return nil, ErrUnexpectedTrailer
753 // body turns a Reader into a ReadCloser.
754 // Close ensures that the body has been fully read
755 // and then reads the trailer if necessary.
758 hdr interface{} // non-nil (Response or Request) value means read trailer
759 r *bufio.Reader // underlying wire-format reader for the trailer
760 closing bool // is the connection to be closed after reading body?
761 doEarlyClose bool // whether Close should stop early
763 mu sync.Mutex // guards following, and calls to Read and Close
766 earlyClose bool // Close called and we didn't read to the end of src
767 onHitEOF func() // if non-nil, func to call when EOF is Read
770 // ErrBodyReadAfterClose is returned when reading a Request or Response
771 // Body after the body has been closed. This typically happens when the body is
772 // read after an HTTP Handler calls WriteHeader or Write on its
774 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
776 func (b *body) Read(p []byte) (n int, err error) {
780 return 0, ErrBodyReadAfterClose
782 return b.readLocked(p)
786 func (b *body) readLocked(p []byte) (n int, err error) {
790 n, err = b.src.Read(p)
794 // Chunked case. Read the trailer.
796 if e := b.readTrailer(); e != nil {
798 // Something went wrong in the trailer, we must not allow any
799 // further reads of any kind to succeed from body, nor any
800 // subsequent requests on the server connection. See
801 // golang.org/issue/12027
807 // If the server declared the Content-Length, our body is a LimitedReader
808 // and we need to check whether this EOF arrived early.
809 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
810 err = io.ErrUnexpectedEOF
815 // If we can return an EOF here along with the read data, do
816 // so. This is optional per the io.Reader contract, but doing
817 // so helps the HTTP transport code recycle its connection
818 // earlier (since it will see this EOF itself), even if the
819 // client doesn't do future reads or Close.
820 if err == nil && n > 0 {
821 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
827 if b.sawEOF && b.onHitEOF != nil {
835 singleCRLF = []byte("\r\n")
836 doubleCRLF = []byte("\r\n\r\n")
839 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
840 for peekSize := 4; ; peekSize++ {
841 // This loop stops when Peek returns an error,
842 // which it does when r's buffer has been filled.
843 buf, err := r.Peek(peekSize)
844 if bytes.HasSuffix(buf, doubleCRLF) {
854 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
856 func (b *body) readTrailer() error {
857 // The common case, since nobody uses trailers.
858 buf, err := b.r.Peek(2)
859 if bytes.Equal(buf, singleCRLF) {
870 // Make sure there's a header terminator coming up, to prevent
871 // a DoS with an unbounded size Trailer. It's not easy to
872 // slip in a LimitReader here, as textproto.NewReader requires
873 // a concrete *bufio.Reader. Also, we can't get all the way
874 // back up to our conn's LimitedReader that *might* be backing
875 // this bufio.Reader. Instead, a hack: we iteratively Peek up
876 // to the bufio.Reader's max size, looking for a double CRLF.
877 // This limits the trailer to the underlying buffer size, typically 4kB.
878 if !seeUpcomingDoubleCRLF(b.r) {
879 return errors.New("http: suspiciously long trailer after chunked body")
882 hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
889 switch rr := b.hdr.(type) {
891 mergeSetHeader(&rr.Trailer, Header(hdr))
893 mergeSetHeader(&rr.Trailer, Header(hdr))
898 func mergeSetHeader(dst *Header, src Header) {
903 for k, vv := range src {
908 // unreadDataSizeLocked returns the number of bytes of unread input.
909 // It returns -1 if unknown.
910 // b.mu must be held.
911 func (b *body) unreadDataSizeLocked() int64 {
912 if lr, ok := b.src.(*io.LimitedReader); ok {
918 func (b *body) Close() error {
927 // Already saw EOF, so no need going to look for it.
928 case b.hdr == nil && b.closing:
929 // no trailer and closing the connection next.
930 // no point in reading to EOF.
932 // Read up to maxPostHandlerReadBytes bytes of the body, looking for
933 // for EOF (and trailers), so we can re-use this connection.
934 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
935 // There was a declared Content-Length, and we have more bytes remaining
936 // than our maxPostHandlerReadBytes tolerance. So, give up.
940 // Consume the body, or, which will also lead to us reading
941 // the trailer headers after the body, if present.
942 n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
946 if n == maxPostHandlerReadBytes {
951 // Fully consume the body, which will also lead to us reading
952 // the trailer headers after the body, if present.
953 _, err = io.Copy(ioutil.Discard, bodyLocked{b})
959 func (b *body) didEarlyClose() bool {
965 // bodyRemains reports whether future Read calls might
967 func (b *body) bodyRemains() bool {
973 func (b *body) registerOnHitEOF(fn func()) {
979 // bodyLocked is a io.Reader reading from a *body when its mutex is
981 type bodyLocked struct {
985 func (bl bodyLocked) Read(p []byte) (n int, err error) {
987 return 0, ErrBodyReadAfterClose
989 return bl.b.readLocked(p)
992 // parseContentLength trims whitespace from s and returns -1 if no value
993 // is set, or the value if it's >= 0.
994 func parseContentLength(cl string) (int64, error) {
995 cl = strings.TrimSpace(cl)
999 n, err := strconv.ParseInt(cl, 10, 64)
1000 if err != nil || n < 0 {
1001 return 0, &badStringError{"bad Content-Length", cl}
1007 // finishAsyncByteRead finishes reading the 1-byte sniff
1008 // from the ContentLength==0, Body!=nil case.
1009 type finishAsyncByteRead struct {
1013 func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1017 rres := <-fr.tw.ByteReadCh
1018 n, err = rres.n, rres.err
1025 var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))
1027 // isKnownInMemoryReader reports whether r is a type known to not
1028 // block on Read. Its caller uses this as an optional optimization to
1029 // send fewer TCP packets.
1030 func isKnownInMemoryReader(r io.Reader) bool {
1032 case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1035 if reflect.TypeOf(r) == nopCloserType {
1036 return isKnownInMemoryReader(reflect.ValueOf(r).Field(0).Interface().(io.Reader))