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.
24 "golang_org/x/net/http/httpguts"
27 // ErrLineTooLong is returned when reading request or response bodies
28 // with malformed chunked encoding.
29 var ErrLineTooLong = internal.ErrLineTooLong
31 type errorReader struct {
35 func (r errorReader) Read(p []byte) (n int, err error) {
39 type byteReader struct {
44 func (br *byteReader) Read(p []byte) (n int, err error) {
56 // transferBodyReader is an io.Reader that reads from tw.Body
57 // and records any non-EOF error in tw.bodyReadError.
58 // It is exactly 1 pointer wide to avoid allocations into interfaces.
59 type transferBodyReader struct{ tw *transferWriter }
61 func (br transferBodyReader) Read(p []byte) (n int, err error) {
62 n, err = br.tw.Body.Read(p)
63 if err != nil && err != io.EOF {
64 br.tw.bodyReadError = err
69 // transferWriter inspects the fields of a user-supplied Request or Response,
70 // sanitizes them without changing the user object and provides methods for
71 // writing the respective header, body and trailer in wire format.
72 type transferWriter struct {
77 ContentLength int64 // -1 means unknown, 0 means exactly none
79 TransferEncoding []string
83 bodyReadError error // any non-EOF error from reading Body
85 FlushHeaders bool // flush headers to network before body
86 ByteReadCh chan readResult // non-nil if probeRequestBody called
89 func newTransferWriter(r interface{}) (t *transferWriter, err error) {
92 // Extract relevant fields
93 atLeastHTTP11 := false
94 switch rr := r.(type) {
96 if rr.ContentLength != 0 && rr.Body == nil {
97 return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
99 t.Method = valueOrDefault(rr.Method, "GET")
101 t.TransferEncoding = rr.TransferEncoding
103 t.Trailer = rr.Trailer
105 t.BodyCloser = rr.Body
106 t.ContentLength = rr.outgoingLength()
107 if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
108 t.TransferEncoding = []string{"chunked"}
110 // If there's a body, conservatively flush the headers
111 // to any bufio.Writer we're writing to, just in case
112 // the server needs the headers early, before we copy
113 // the body and possibly block. We make an exception
114 // for the common standard library in-memory types,
115 // though, to avoid unnecessary TCP packets on the
116 // wire. (Issue 22088.)
117 if t.ContentLength != 0 && !isKnownInMemoryReader(t.Body) {
118 t.FlushHeaders = true
121 atLeastHTTP11 = true // Transport requests are always 1.1 or 2.0
124 if rr.Request != nil {
125 t.Method = rr.Request.Method
128 t.BodyCloser = rr.Body
129 t.ContentLength = rr.ContentLength
131 t.TransferEncoding = rr.TransferEncoding
133 t.Trailer = rr.Trailer
134 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
135 t.ResponseToHEAD = noResponseBodyExpected(t.Method)
138 // Sanitize Body,ContentLength,TransferEncoding
139 if t.ResponseToHEAD {
141 if chunked(t.TransferEncoding) {
145 if !atLeastHTTP11 || t.Body == nil {
146 t.TransferEncoding = nil
148 if chunked(t.TransferEncoding) {
150 } else if t.Body == nil { // no chunking, no body
156 if !chunked(t.TransferEncoding) {
163 // shouldSendChunkedRequestBody reports whether we should try to send a
164 // chunked request body to the server. In particular, the case we really
165 // want to prevent is sending a GET or other typically-bodyless request to a
166 // server with a chunked body when the body has zero bytes, since GETs with
167 // bodies (while acceptable according to specs), even zero-byte chunked
168 // bodies, are approximately never seen in the wild and confuse most
169 // servers. See Issue 18257, as one example.
171 // The only reason we'd send such a request is if the user set the Body to a
172 // non-nil value (say, ioutil.NopCloser(bytes.NewReader(nil))) and didn't
173 // set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
174 // there's bytes to send.
176 // This code tries to read a byte from the Request.Body in such cases to see
177 // whether the body actually has content (super rare) or is actually just
178 // a non-nil content-less ReadCloser (the more common case). In that more
179 // common case, we act as if their Body were nil instead, and don't send
181 func (t *transferWriter) shouldSendChunkedRequestBody() bool {
182 // Note that t.ContentLength is the corrected content length
183 // from rr.outgoingLength, so 0 actually means zero, not unknown.
184 if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
187 if t.Method == "CONNECT" {
190 if requestMethodUsuallyLacksBody(t.Method) {
191 // Only probe the Request.Body for GET/HEAD/DELETE/etc
192 // requests, because it's only those types of requests
193 // that confuse servers.
194 t.probeRequestBody() // adjusts t.Body, t.ContentLength
197 // For all other request types (PUT, POST, PATCH, or anything
198 // made-up we've never heard of), assume it's normal and the server
199 // can deal with a chunked request body. Maybe we'll adjust this
204 // probeRequestBody reads a byte from t.Body to see whether it's empty
205 // (returns io.EOF right away).
207 // But because we've had problems with this blocking users in the past
208 // (issue 17480) when the body is a pipe (perhaps waiting on the response
209 // headers before the pipe is fed data), we need to be careful and bound how
210 // long we wait for it. This delay will only affect users if all the following
212 // * the request body blocks
213 // * the content length is not set (or set to -1)
214 // * the method doesn't usually have a body (GET, HEAD, DELETE, ...)
215 // * there is no transfer-encoding=chunked already set.
216 // In other words, this delay will not normally affect anybody, and there
217 // are workarounds if it does.
218 func (t *transferWriter) probeRequestBody() {
219 t.ByteReadCh = make(chan readResult, 1)
220 go func(body io.Reader) {
223 rres.n, rres.err = body.Read(buf[:])
229 timer := time.NewTimer(200 * time.Millisecond)
231 case rres := <-t.ByteReadCh:
233 if rres.n == 0 && rres.err == io.EOF {
237 } else if rres.n == 1 {
239 t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
241 t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
243 } else if rres.err != nil {
244 t.Body = errorReader{rres.err}
247 // Too slow. Don't wait. Read it later, and keep
248 // assuming that this is ContentLength == -1
249 // (unknown), which means we'll send a
250 // "Transfer-Encoding: chunked" header.
251 t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
252 // Request that Request.Write flush the headers to the
253 // network before writing the body, since our body may not
254 // become readable until it's seen the response headers.
255 t.FlushHeaders = true
259 func noResponseBodyExpected(requestMethod string) bool {
260 return requestMethod == "HEAD"
263 func (t *transferWriter) shouldSendContentLength() bool {
264 if chunked(t.TransferEncoding) {
267 if t.ContentLength > 0 {
270 if t.ContentLength < 0 {
273 // Many servers expect a Content-Length for these methods
274 if t.Method == "POST" || t.Method == "PUT" {
277 if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
278 if t.Method == "GET" || t.Method == "HEAD" {
287 func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error {
288 if t.Close && !hasToken(t.Header.get("Connection"), "close") {
289 if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
292 if trace != nil && trace.WroteHeaderField != nil {
293 trace.WroteHeaderField("Connection", []string{"close"})
297 // Write Content-Length and/or Transfer-Encoding whose values are a
298 // function of the sanitized field triple (Body, ContentLength,
300 if t.shouldSendContentLength() {
301 if _, err := io.WriteString(w, "Content-Length: "); err != nil {
304 if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
307 if trace != nil && trace.WroteHeaderField != nil {
308 trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
310 } else if chunked(t.TransferEncoding) {
311 if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
314 if trace != nil && trace.WroteHeaderField != nil {
315 trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
319 // Write Trailer header
320 if t.Trailer != nil {
321 keys := make([]string, 0, len(t.Trailer))
322 for k := range t.Trailer {
323 k = CanonicalHeaderKey(k)
325 case "Transfer-Encoding", "Trailer", "Content-Length":
326 return &badStringError{"invalid Trailer key", k}
328 keys = append(keys, k)
332 // TODO: could do better allocation-wise here, but trailers are rare,
333 // so being lazy for now.
334 if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
337 if trace != nil && trace.WroteHeaderField != nil {
338 trace.WroteHeaderField("Trailer", keys)
346 func (t *transferWriter) writeBody(w io.Writer) error {
352 var body = transferBodyReader{t}
353 if chunked(t.TransferEncoding) {
354 if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
355 w = &internal.FlushAfterChunkWriter{Writer: bw}
357 cw := internal.NewChunkedWriter(w)
358 _, err = io.Copy(cw, body)
362 } else if t.ContentLength == -1 {
364 if t.Method == "CONNECT" {
365 dst = bufioFlushWriter{dst}
367 ncopy, err = io.Copy(dst, body)
369 ncopy, err = io.Copy(w, io.LimitReader(body, t.ContentLength))
374 nextra, err = io.Copy(ioutil.Discard, body)
381 if t.BodyCloser != nil {
382 if err := t.BodyCloser.Close(); err != nil {
387 if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
388 return fmt.Errorf("http: ContentLength=%d with Body length %d",
389 t.ContentLength, ncopy)
392 if chunked(t.TransferEncoding) {
393 // Write Trailer header
394 if t.Trailer != nil {
395 if err := t.Trailer.Write(w); err != nil {
399 // Last chunk, empty trailer
400 _, err = io.WriteString(w, "\r\n")
405 type transferReader struct {
415 TransferEncoding []string
420 func (t *transferReader) protoAtLeast(m, n int) bool {
421 return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
424 // bodyAllowedForStatus reports whether a given response status code
425 // permits a body. See RFC 7230, section 3.3.
426 func bodyAllowedForStatus(status int) bool {
428 case status >= 100 && status <= 199:
439 suppressedHeaders304 = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
440 suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
443 func suppressedHeaders(status int) []string {
446 // RFC 7232 section 4.1
447 return suppressedHeaders304
448 case !bodyAllowedForStatus(status):
449 return suppressedHeadersNoBody
454 // msg is *Request or *Response.
455 func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
456 t := &transferReader{RequestMethod: "GET"}
460 switch rr := msg.(type) {
463 t.StatusCode = rr.StatusCode
464 t.ProtoMajor = rr.ProtoMajor
465 t.ProtoMinor = rr.ProtoMinor
466 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
468 if rr.Request != nil {
469 t.RequestMethod = rr.Request.Method
473 t.RequestMethod = rr.Method
474 t.ProtoMajor = rr.ProtoMajor
475 t.ProtoMinor = rr.ProtoMinor
476 // Transfer semantics for Requests are exactly like those for
477 // Responses with status code 200, responding to a GET method
481 panic("unexpected type")
484 // Default to HTTP/1.1
485 if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
486 t.ProtoMajor, t.ProtoMinor = 1, 1
489 // Transfer encoding, content length
490 err = t.fixTransferEncoding()
495 realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
499 if isResponse && t.RequestMethod == "HEAD" {
500 if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
506 t.ContentLength = realLength
510 t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
515 // If there is no Content-Length or chunked Transfer-Encoding on a *Response
516 // and the status is not 1xx, 204 or 304, then the body is unbounded.
517 // See RFC 7230, section 3.3.
520 if realLength == -1 &&
521 !chunked(t.TransferEncoding) &&
522 bodyAllowedForStatus(t.StatusCode) {
528 // Prepare body reader. ContentLength < 0 means chunked encoding
529 // or close connection when finished, since multipart is not supported yet
531 case chunked(t.TransferEncoding):
532 if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
535 t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
537 case realLength == 0:
540 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
542 // realLength < 0, i.e. "Content-Length" not mentioned in header
544 // Close semantics (i.e. HTTP/1.0)
545 t.Body = &body{src: r, closing: t.Close}
547 // Persistent connection (i.e. HTTP/1.1)
553 switch rr := msg.(type) {
556 rr.ContentLength = t.ContentLength
557 rr.TransferEncoding = t.TransferEncoding
559 rr.Trailer = t.Trailer
562 rr.ContentLength = t.ContentLength
563 rr.TransferEncoding = t.TransferEncoding
565 rr.Trailer = t.Trailer
571 // Checks whether chunked is part of the encodings stack
572 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
574 // Checks whether the encoding is explicitly "identity".
575 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
577 // fixTransferEncoding sanitizes t.TransferEncoding, if needed.
578 func (t *transferReader) fixTransferEncoding() error {
579 raw, present := t.Header["Transfer-Encoding"]
583 delete(t.Header, "Transfer-Encoding")
585 // Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
586 if !t.protoAtLeast(1, 1) {
590 encodings := strings.Split(raw[0], ",")
591 te := make([]string, 0, len(encodings))
592 // TODO: Even though we only support "identity" and "chunked"
593 // encodings, the loop below is designed with foresight. One
594 // invariant that must be maintained is that, if present,
595 // chunked encoding must always come first.
596 for _, encoding := range encodings {
597 encoding = strings.ToLower(strings.TrimSpace(encoding))
598 // "identity" encoding is not recorded
599 if encoding == "identity" {
602 if encoding != "chunked" {
603 return &badStringError{"unsupported transfer encoding", encoding}
605 te = te[0 : len(te)+1]
606 te[len(te)-1] = encoding
609 return &badStringError{"too many transfer encodings", strings.Join(te, ",")}
612 // RFC 7230 3.3.2 says "A sender MUST NOT send a
613 // Content-Length header field in any message that
614 // contains a Transfer-Encoding header field."
617 // "If a message is received with both a
618 // Transfer-Encoding and a Content-Length header
619 // field, the Transfer-Encoding overrides the
620 // Content-Length. Such a message might indicate an
621 // attempt to perform request smuggling (Section 9.5)
622 // or response splitting (Section 9.4) and ought to be
623 // handled as an error. A sender MUST remove the
624 // received Content-Length field prior to forwarding
625 // such a message downstream."
627 // Reportedly, these appear in the wild.
628 delete(t.Header, "Content-Length")
629 t.TransferEncoding = te
636 // Determine the expected body length, using RFC 7230 Section 3.3. This
637 // function is not a method, because ultimately it should be shared by
638 // ReadResponse and ReadRequest.
639 func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
640 isRequest := !isResponse
641 contentLens := header["Content-Length"]
643 // Hardening against HTTP request smuggling
644 if len(contentLens) > 1 {
645 // Per RFC 7230 Section 3.3.2, prevent multiple
646 // Content-Length headers if they differ in value.
647 // If there are dups of the value, remove the dups.
649 first := strings.TrimSpace(contentLens[0])
650 for _, ct := range contentLens[1:] {
651 if first != strings.TrimSpace(ct) {
652 return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
656 // deduplicate Content-Length
657 header.Del("Content-Length")
658 header.Add("Content-Length", first)
660 contentLens = header["Content-Length"]
663 // Logic based on response type or status
664 if noResponseBodyExpected(requestMethod) {
665 // For HTTP requests, as part of hardening against request
666 // smuggling (RFC 7230), don't allow a Content-Length header for
667 // methods which don't permit bodies. As an exception, allow
668 // exactly one Content-Length header if its value is "0".
669 if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
670 return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
682 // Logic based on Transfer-Encoding
687 // Logic based on Content-Length
689 if len(contentLens) == 1 {
690 cl = strings.TrimSpace(contentLens[0])
693 n, err := parseContentLength(cl)
699 header.Del("Content-Length")
702 // RFC 7230 neither explicitly permits nor forbids an
703 // entity-body on a GET request so we permit one if
704 // declared, but we default to 0 here (not -1 below)
705 // if there's no mention of a body.
706 // Likewise, all other request methods are assumed to have
707 // no body if neither Transfer-Encoding chunked nor a
708 // Content-Length are set.
712 // Body-EOF logic based on other methods (like closing, or chunked coding)
716 // Determine whether to hang up after sending a request and body, or
717 // receiving a response and body
718 // 'header' is the request headers
719 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
724 conv := header["Connection"]
725 hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
726 if major == 1 && minor == 0 {
727 return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
730 if hasClose && removeCloseHeader {
731 header.Del("Connection")
737 // Parse the trailer header
738 func fixTrailer(header Header, te []string) (Header, error) {
739 vv, ok := header["Trailer"]
743 header.Del("Trailer")
745 trailer := make(Header)
747 for _, v := range vv {
748 foreachHeaderElement(v, func(key string) {
749 key = CanonicalHeaderKey(key)
751 case "Transfer-Encoding", "Trailer", "Content-Length":
753 err = &badStringError{"bad trailer key", key}
763 if len(trailer) == 0 {
767 // Trailer and no chunking
768 return nil, ErrUnexpectedTrailer
773 // body turns a Reader into a ReadCloser.
774 // Close ensures that the body has been fully read
775 // and then reads the trailer if necessary.
778 hdr interface{} // non-nil (Response or Request) value means read trailer
779 r *bufio.Reader // underlying wire-format reader for the trailer
780 closing bool // is the connection to be closed after reading body?
781 doEarlyClose bool // whether Close should stop early
783 mu sync.Mutex // guards following, and calls to Read and Close
786 earlyClose bool // Close called and we didn't read to the end of src
787 onHitEOF func() // if non-nil, func to call when EOF is Read
790 // ErrBodyReadAfterClose is returned when reading a Request or Response
791 // Body after the body has been closed. This typically happens when the body is
792 // read after an HTTP Handler calls WriteHeader or Write on its
794 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
796 func (b *body) Read(p []byte) (n int, err error) {
800 return 0, ErrBodyReadAfterClose
802 return b.readLocked(p)
806 func (b *body) readLocked(p []byte) (n int, err error) {
810 n, err = b.src.Read(p)
814 // Chunked case. Read the trailer.
816 if e := b.readTrailer(); e != nil {
818 // Something went wrong in the trailer, we must not allow any
819 // further reads of any kind to succeed from body, nor any
820 // subsequent requests on the server connection. See
821 // golang.org/issue/12027
827 // If the server declared the Content-Length, our body is a LimitedReader
828 // and we need to check whether this EOF arrived early.
829 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
830 err = io.ErrUnexpectedEOF
835 // If we can return an EOF here along with the read data, do
836 // so. This is optional per the io.Reader contract, but doing
837 // so helps the HTTP transport code recycle its connection
838 // earlier (since it will see this EOF itself), even if the
839 // client doesn't do future reads or Close.
840 if err == nil && n > 0 {
841 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
847 if b.sawEOF && b.onHitEOF != nil {
855 singleCRLF = []byte("\r\n")
856 doubleCRLF = []byte("\r\n\r\n")
859 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
860 for peekSize := 4; ; peekSize++ {
861 // This loop stops when Peek returns an error,
862 // which it does when r's buffer has been filled.
863 buf, err := r.Peek(peekSize)
864 if bytes.HasSuffix(buf, doubleCRLF) {
874 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
876 func (b *body) readTrailer() error {
877 // The common case, since nobody uses trailers.
878 buf, err := b.r.Peek(2)
879 if bytes.Equal(buf, singleCRLF) {
890 // Make sure there's a header terminator coming up, to prevent
891 // a DoS with an unbounded size Trailer. It's not easy to
892 // slip in a LimitReader here, as textproto.NewReader requires
893 // a concrete *bufio.Reader. Also, we can't get all the way
894 // back up to our conn's LimitedReader that *might* be backing
895 // this bufio.Reader. Instead, a hack: we iteratively Peek up
896 // to the bufio.Reader's max size, looking for a double CRLF.
897 // This limits the trailer to the underlying buffer size, typically 4kB.
898 if !seeUpcomingDoubleCRLF(b.r) {
899 return errors.New("http: suspiciously long trailer after chunked body")
902 hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
909 switch rr := b.hdr.(type) {
911 mergeSetHeader(&rr.Trailer, Header(hdr))
913 mergeSetHeader(&rr.Trailer, Header(hdr))
918 func mergeSetHeader(dst *Header, src Header) {
923 for k, vv := range src {
928 // unreadDataSizeLocked returns the number of bytes of unread input.
929 // It returns -1 if unknown.
930 // b.mu must be held.
931 func (b *body) unreadDataSizeLocked() int64 {
932 if lr, ok := b.src.(*io.LimitedReader); ok {
938 func (b *body) Close() error {
947 // Already saw EOF, so no need going to look for it.
948 case b.hdr == nil && b.closing:
949 // no trailer and closing the connection next.
950 // no point in reading to EOF.
952 // Read up to maxPostHandlerReadBytes bytes of the body, looking
953 // for EOF (and trailers), so we can re-use this connection.
954 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
955 // There was a declared Content-Length, and we have more bytes remaining
956 // than our maxPostHandlerReadBytes tolerance. So, give up.
960 // Consume the body, or, which will also lead to us reading
961 // the trailer headers after the body, if present.
962 n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
966 if n == maxPostHandlerReadBytes {
971 // Fully consume the body, which will also lead to us reading
972 // the trailer headers after the body, if present.
973 _, err = io.Copy(ioutil.Discard, bodyLocked{b})
979 func (b *body) didEarlyClose() bool {
985 // bodyRemains reports whether future Read calls might
987 func (b *body) bodyRemains() bool {
993 func (b *body) registerOnHitEOF(fn func()) {
999 // bodyLocked is a io.Reader reading from a *body when its mutex is
1001 type bodyLocked struct {
1005 func (bl bodyLocked) Read(p []byte) (n int, err error) {
1007 return 0, ErrBodyReadAfterClose
1009 return bl.b.readLocked(p)
1012 // parseContentLength trims whitespace from s and returns -1 if no value
1013 // is set, or the value if it's >= 0.
1014 func parseContentLength(cl string) (int64, error) {
1015 cl = strings.TrimSpace(cl)
1019 n, err := strconv.ParseInt(cl, 10, 64)
1020 if err != nil || n < 0 {
1021 return 0, &badStringError{"bad Content-Length", cl}
1027 // finishAsyncByteRead finishes reading the 1-byte sniff
1028 // from the ContentLength==0, Body!=nil case.
1029 type finishAsyncByteRead struct {
1033 func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1037 rres := <-fr.tw.ByteReadCh
1038 n, err = rres.n, rres.err
1045 var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))
1047 // isKnownInMemoryReader reports whether r is a type known to not
1048 // block on Read. Its caller uses this as an optional optimization to
1049 // send fewer TCP packets.
1050 func isKnownInMemoryReader(r io.Reader) bool {
1052 case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1055 if reflect.TypeOf(r) == nopCloserType {
1056 return isKnownInMemoryReader(reflect.ValueOf(r).Field(0).Interface().(io.Reader))
1061 // bufioFlushWriter is an io.Writer wrapper that flushes all writes
1062 // on its wrapped writer if it's a *bufio.Writer.
1063 type bufioFlushWriter struct{ w io.Writer }
1065 func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
1066 n, err = fw.w.Write(p)
1067 if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
1069 if ferr != nil && err == nil {