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 "internal/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 // transferWriter inspects the fields of a user-supplied Request or Response,
57 // sanitizes them without changing the user object and provides methods for
58 // writing the respective header, body and trailer in wire format.
59 type transferWriter struct {
64 ContentLength int64 // -1 means unknown, 0 means exactly none
66 TransferEncoding []string
70 bodyReadError error // any non-EOF error from reading Body
72 FlushHeaders bool // flush headers to network before body
73 ByteReadCh chan readResult // non-nil if probeRequestBody called
76 func newTransferWriter(r interface{}) (t *transferWriter, err error) {
79 // Extract relevant fields
80 atLeastHTTP11 := false
81 switch rr := r.(type) {
83 if rr.ContentLength != 0 && rr.Body == nil {
84 return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
86 t.Method = valueOrDefault(rr.Method, "GET")
88 t.TransferEncoding = rr.TransferEncoding
90 t.Trailer = rr.Trailer
92 t.BodyCloser = rr.Body
93 t.ContentLength = rr.outgoingLength()
94 if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
95 t.TransferEncoding = []string{"chunked"}
97 // If there's a body, conservatively flush the headers
98 // to any bufio.Writer we're writing to, just in case
99 // the server needs the headers early, before we copy
100 // the body and possibly block. We make an exception
101 // for the common standard library in-memory types,
102 // though, to avoid unnecessary TCP packets on the
103 // wire. (Issue 22088.)
104 if t.ContentLength != 0 && !isKnownInMemoryReader(t.Body) {
105 t.FlushHeaders = true
108 atLeastHTTP11 = true // Transport requests are always 1.1 or 2.0
111 if rr.Request != nil {
112 t.Method = rr.Request.Method
115 t.BodyCloser = rr.Body
116 t.ContentLength = rr.ContentLength
118 t.TransferEncoding = rr.TransferEncoding
120 t.Trailer = rr.Trailer
121 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
122 t.ResponseToHEAD = noResponseBodyExpected(t.Method)
125 // Sanitize Body,ContentLength,TransferEncoding
126 if t.ResponseToHEAD {
128 if chunked(t.TransferEncoding) {
132 if !atLeastHTTP11 || t.Body == nil {
133 t.TransferEncoding = nil
135 if chunked(t.TransferEncoding) {
137 } else if t.Body == nil { // no chunking, no body
143 if !chunked(t.TransferEncoding) {
150 // shouldSendChunkedRequestBody reports whether we should try to send a
151 // chunked request body to the server. In particular, the case we really
152 // want to prevent is sending a GET or other typically-bodyless request to a
153 // server with a chunked body when the body has zero bytes, since GETs with
154 // bodies (while acceptable according to specs), even zero-byte chunked
155 // bodies, are approximately never seen in the wild and confuse most
156 // servers. See Issue 18257, as one example.
158 // The only reason we'd send such a request is if the user set the Body to a
159 // non-nil value (say, ioutil.NopCloser(bytes.NewReader(nil))) and didn't
160 // set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
161 // there's bytes to send.
163 // This code tries to read a byte from the Request.Body in such cases to see
164 // whether the body actually has content (super rare) or is actually just
165 // a non-nil content-less ReadCloser (the more common case). In that more
166 // common case, we act as if their Body were nil instead, and don't send
168 func (t *transferWriter) shouldSendChunkedRequestBody() bool {
169 // Note that t.ContentLength is the corrected content length
170 // from rr.outgoingLength, so 0 actually means zero, not unknown.
171 if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
174 if t.Method == "CONNECT" {
177 if requestMethodUsuallyLacksBody(t.Method) {
178 // Only probe the Request.Body for GET/HEAD/DELETE/etc
179 // requests, because it's only those types of requests
180 // that confuse servers.
181 t.probeRequestBody() // adjusts t.Body, t.ContentLength
184 // For all other request types (PUT, POST, PATCH, or anything
185 // made-up we've never heard of), assume it's normal and the server
186 // can deal with a chunked request body. Maybe we'll adjust this
191 // probeRequestBody reads a byte from t.Body to see whether it's empty
192 // (returns io.EOF right away).
194 // But because we've had problems with this blocking users in the past
195 // (issue 17480) when the body is a pipe (perhaps waiting on the response
196 // headers before the pipe is fed data), we need to be careful and bound how
197 // long we wait for it. This delay will only affect users if all the following
199 // * the request body blocks
200 // * the content length is not set (or set to -1)
201 // * the method doesn't usually have a body (GET, HEAD, DELETE, ...)
202 // * there is no transfer-encoding=chunked already set.
203 // In other words, this delay will not normally affect anybody, and there
204 // are workarounds if it does.
205 func (t *transferWriter) probeRequestBody() {
206 t.ByteReadCh = make(chan readResult, 1)
207 go func(body io.Reader) {
210 rres.n, rres.err = body.Read(buf[:])
216 timer := time.NewTimer(200 * time.Millisecond)
218 case rres := <-t.ByteReadCh:
220 if rres.n == 0 && rres.err == io.EOF {
224 } else if rres.n == 1 {
226 t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
228 t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
230 } else if rres.err != nil {
231 t.Body = errorReader{rres.err}
234 // Too slow. Don't wait. Read it later, and keep
235 // assuming that this is ContentLength == -1
236 // (unknown), which means we'll send a
237 // "Transfer-Encoding: chunked" header.
238 t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
239 // Request that Request.Write flush the headers to the
240 // network before writing the body, since our body may not
241 // become readable until it's seen the response headers.
242 t.FlushHeaders = true
246 func noResponseBodyExpected(requestMethod string) bool {
247 return requestMethod == "HEAD"
250 func (t *transferWriter) shouldSendContentLength() bool {
251 if chunked(t.TransferEncoding) {
254 if t.ContentLength > 0 {
257 if t.ContentLength < 0 {
260 // Many servers expect a Content-Length for these methods
261 if t.Method == "POST" || t.Method == "PUT" {
264 if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
265 if t.Method == "GET" || t.Method == "HEAD" {
274 func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error {
275 if t.Close && !hasToken(t.Header.get("Connection"), "close") {
276 if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
279 if trace != nil && trace.WroteHeaderField != nil {
280 trace.WroteHeaderField("Connection", []string{"close"})
284 // Write Content-Length and/or Transfer-Encoding whose values are a
285 // function of the sanitized field triple (Body, ContentLength,
287 if t.shouldSendContentLength() {
288 if _, err := io.WriteString(w, "Content-Length: "); err != nil {
291 if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
294 if trace != nil && trace.WroteHeaderField != nil {
295 trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
297 } else if chunked(t.TransferEncoding) {
298 if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
301 if trace != nil && trace.WroteHeaderField != nil {
302 trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
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 {
324 if trace != nil && trace.WroteHeaderField != nil {
325 trace.WroteHeaderField("Trailer", keys)
333 func (t *transferWriter) writeBody(w io.Writer) error {
337 // Write body. We "unwrap" the body first if it was wrapped in a
338 // nopCloser. This is to ensure that we can take advantage of
339 // OS-level optimizations in the event that the body is an
342 var body = t.unwrapBody()
343 if chunked(t.TransferEncoding) {
344 if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
345 w = &internal.FlushAfterChunkWriter{Writer: bw}
347 cw := internal.NewChunkedWriter(w)
348 _, err = t.doBodyCopy(cw, body)
352 } else if t.ContentLength == -1 {
354 if t.Method == "CONNECT" {
355 dst = bufioFlushWriter{dst}
357 ncopy, err = t.doBodyCopy(dst, body)
359 ncopy, err = t.doBodyCopy(w, io.LimitReader(body, t.ContentLength))
364 nextra, err = t.doBodyCopy(ioutil.Discard, body)
371 if t.BodyCloser != nil {
372 if err := t.BodyCloser.Close(); err != nil {
377 if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
378 return fmt.Errorf("http: ContentLength=%d with Body length %d",
379 t.ContentLength, ncopy)
382 if chunked(t.TransferEncoding) {
383 // Write Trailer header
384 if t.Trailer != nil {
385 if err := t.Trailer.Write(w); err != nil {
389 // Last chunk, empty trailer
390 _, err = io.WriteString(w, "\r\n")
395 // doBodyCopy wraps a copy operation, with any resulting error also
396 // being saved in bodyReadError.
398 // This function is only intended for use in writeBody.
399 func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
400 n, err = io.Copy(dst, src)
401 if err != nil && err != io.EOF {
402 t.bodyReadError = err
407 // unwrapBodyReader unwraps the body's inner reader if it's a
408 // nopCloser. This is to ensure that body writes sourced from local
409 // files (*os.File types) are properly optimized.
411 // This function is only intended for use in writeBody.
412 func (t *transferWriter) unwrapBody() io.Reader {
413 if reflect.TypeOf(t.Body) == nopCloserType {
414 return reflect.ValueOf(t.Body).Field(0).Interface().(io.Reader)
420 type transferReader struct {
430 TransferEncoding []string
435 func (t *transferReader) protoAtLeast(m, n int) bool {
436 return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
439 // bodyAllowedForStatus reports whether a given response status code
440 // permits a body. See RFC 7230, section 3.3.
441 func bodyAllowedForStatus(status int) bool {
443 case status >= 100 && status <= 199:
454 suppressedHeaders304 = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
455 suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
458 func suppressedHeaders(status int) []string {
461 // RFC 7232 section 4.1
462 return suppressedHeaders304
463 case !bodyAllowedForStatus(status):
464 return suppressedHeadersNoBody
469 // msg is *Request or *Response.
470 func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
471 t := &transferReader{RequestMethod: "GET"}
475 switch rr := msg.(type) {
478 t.StatusCode = rr.StatusCode
479 t.ProtoMajor = rr.ProtoMajor
480 t.ProtoMinor = rr.ProtoMinor
481 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
483 if rr.Request != nil {
484 t.RequestMethod = rr.Request.Method
488 t.RequestMethod = rr.Method
489 t.ProtoMajor = rr.ProtoMajor
490 t.ProtoMinor = rr.ProtoMinor
491 // Transfer semantics for Requests are exactly like those for
492 // Responses with status code 200, responding to a GET method
496 panic("unexpected type")
499 // Default to HTTP/1.1
500 if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
501 t.ProtoMajor, t.ProtoMinor = 1, 1
504 // Transfer encoding, content length
505 err = t.fixTransferEncoding()
510 realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
514 if isResponse && t.RequestMethod == "HEAD" {
515 if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
521 t.ContentLength = realLength
525 t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
530 // If there is no Content-Length or chunked Transfer-Encoding on a *Response
531 // and the status is not 1xx, 204 or 304, then the body is unbounded.
532 // See RFC 7230, section 3.3.
535 if realLength == -1 &&
536 !chunked(t.TransferEncoding) &&
537 bodyAllowedForStatus(t.StatusCode) {
543 // Prepare body reader. ContentLength < 0 means chunked encoding
544 // or close connection when finished, since multipart is not supported yet
546 case chunked(t.TransferEncoding):
547 if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
550 t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
552 case realLength == 0:
555 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
557 // realLength < 0, i.e. "Content-Length" not mentioned in header
559 // Close semantics (i.e. HTTP/1.0)
560 t.Body = &body{src: r, closing: t.Close}
562 // Persistent connection (i.e. HTTP/1.1)
568 switch rr := msg.(type) {
571 rr.ContentLength = t.ContentLength
572 rr.TransferEncoding = t.TransferEncoding
574 rr.Trailer = t.Trailer
577 rr.ContentLength = t.ContentLength
578 rr.TransferEncoding = t.TransferEncoding
580 rr.Trailer = t.Trailer
586 // Checks whether chunked is part of the encodings stack
587 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
589 // Checks whether the encoding is explicitly "identity".
590 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
592 // fixTransferEncoding sanitizes t.TransferEncoding, if needed.
593 func (t *transferReader) fixTransferEncoding() error {
594 raw, present := t.Header["Transfer-Encoding"]
598 delete(t.Header, "Transfer-Encoding")
600 // Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
601 if !t.protoAtLeast(1, 1) {
605 encodings := strings.Split(raw[0], ",")
606 te := make([]string, 0, len(encodings))
607 // TODO: Even though we only support "identity" and "chunked"
608 // encodings, the loop below is designed with foresight. One
609 // invariant that must be maintained is that, if present,
610 // chunked encoding must always come first.
611 for _, encoding := range encodings {
612 encoding = strings.ToLower(strings.TrimSpace(encoding))
613 // "identity" encoding is not recorded
614 if encoding == "identity" {
617 if encoding != "chunked" {
618 return &badStringError{"unsupported transfer encoding", encoding}
620 te = te[0 : len(te)+1]
621 te[len(te)-1] = encoding
624 return &badStringError{"too many transfer encodings", strings.Join(te, ",")}
627 // RFC 7230 3.3.2 says "A sender MUST NOT send a
628 // Content-Length header field in any message that
629 // contains a Transfer-Encoding header field."
632 // "If a message is received with both a
633 // Transfer-Encoding and a Content-Length header
634 // field, the Transfer-Encoding overrides the
635 // Content-Length. Such a message might indicate an
636 // attempt to perform request smuggling (Section 9.5)
637 // or response splitting (Section 9.4) and ought to be
638 // handled as an error. A sender MUST remove the
639 // received Content-Length field prior to forwarding
640 // such a message downstream."
642 // Reportedly, these appear in the wild.
643 delete(t.Header, "Content-Length")
644 t.TransferEncoding = te
651 // Determine the expected body length, using RFC 7230 Section 3.3. This
652 // function is not a method, because ultimately it should be shared by
653 // ReadResponse and ReadRequest.
654 func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
655 isRequest := !isResponse
656 contentLens := header["Content-Length"]
658 // Hardening against HTTP request smuggling
659 if len(contentLens) > 1 {
660 // Per RFC 7230 Section 3.3.2, prevent multiple
661 // Content-Length headers if they differ in value.
662 // If there are dups of the value, remove the dups.
664 first := strings.TrimSpace(contentLens[0])
665 for _, ct := range contentLens[1:] {
666 if first != strings.TrimSpace(ct) {
667 return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
671 // deduplicate Content-Length
672 header.Del("Content-Length")
673 header.Add("Content-Length", first)
675 contentLens = header["Content-Length"]
678 // Logic based on response type or status
679 if noResponseBodyExpected(requestMethod) {
680 // For HTTP requests, as part of hardening against request
681 // smuggling (RFC 7230), don't allow a Content-Length header for
682 // methods which don't permit bodies. As an exception, allow
683 // exactly one Content-Length header if its value is "0".
684 if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
685 return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
697 // Logic based on Transfer-Encoding
702 // Logic based on Content-Length
704 if len(contentLens) == 1 {
705 cl = strings.TrimSpace(contentLens[0])
708 n, err := parseContentLength(cl)
714 header.Del("Content-Length")
717 // RFC 7230 neither explicitly permits nor forbids an
718 // entity-body on a GET request so we permit one if
719 // declared, but we default to 0 here (not -1 below)
720 // if there's no mention of a body.
721 // Likewise, all other request methods are assumed to have
722 // no body if neither Transfer-Encoding chunked nor a
723 // Content-Length are set.
727 // Body-EOF logic based on other methods (like closing, or chunked coding)
731 // Determine whether to hang up after sending a request and body, or
732 // receiving a response and body
733 // 'header' is the request headers
734 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
739 conv := header["Connection"]
740 hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
741 if major == 1 && minor == 0 {
742 return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
745 if hasClose && removeCloseHeader {
746 header.Del("Connection")
752 // Parse the trailer header
753 func fixTrailer(header Header, te []string) (Header, error) {
754 vv, ok := header["Trailer"]
759 // Trailer and no chunking:
760 // this is an invalid use case for trailer header.
761 // Nevertheless, no error will be returned and we
762 // let users decide if this is a valid HTTP message.
763 // The Trailer header will be kept in Response.Header
764 // but not populate Response.Trailer.
768 header.Del("Trailer")
770 trailer := make(Header)
772 for _, v := range vv {
773 foreachHeaderElement(v, func(key string) {
774 key = CanonicalHeaderKey(key)
776 case "Transfer-Encoding", "Trailer", "Content-Length":
778 err = &badStringError{"bad trailer key", key}
788 if len(trailer) == 0 {
794 // body turns a Reader into a ReadCloser.
795 // Close ensures that the body has been fully read
796 // and then reads the trailer if necessary.
799 hdr interface{} // non-nil (Response or Request) value means read trailer
800 r *bufio.Reader // underlying wire-format reader for the trailer
801 closing bool // is the connection to be closed after reading body?
802 doEarlyClose bool // whether Close should stop early
804 mu sync.Mutex // guards following, and calls to Read and Close
807 earlyClose bool // Close called and we didn't read to the end of src
808 onHitEOF func() // if non-nil, func to call when EOF is Read
811 // ErrBodyReadAfterClose is returned when reading a Request or Response
812 // Body after the body has been closed. This typically happens when the body is
813 // read after an HTTP Handler calls WriteHeader or Write on its
815 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
817 func (b *body) Read(p []byte) (n int, err error) {
821 return 0, ErrBodyReadAfterClose
823 return b.readLocked(p)
827 func (b *body) readLocked(p []byte) (n int, err error) {
831 n, err = b.src.Read(p)
835 // Chunked case. Read the trailer.
837 if e := b.readTrailer(); e != nil {
839 // Something went wrong in the trailer, we must not allow any
840 // further reads of any kind to succeed from body, nor any
841 // subsequent requests on the server connection. See
842 // golang.org/issue/12027
848 // If the server declared the Content-Length, our body is a LimitedReader
849 // and we need to check whether this EOF arrived early.
850 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
851 err = io.ErrUnexpectedEOF
856 // If we can return an EOF here along with the read data, do
857 // so. This is optional per the io.Reader contract, but doing
858 // so helps the HTTP transport code recycle its connection
859 // earlier (since it will see this EOF itself), even if the
860 // client doesn't do future reads or Close.
861 if err == nil && n > 0 {
862 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
868 if b.sawEOF && b.onHitEOF != nil {
876 singleCRLF = []byte("\r\n")
877 doubleCRLF = []byte("\r\n\r\n")
880 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
881 for peekSize := 4; ; peekSize++ {
882 // This loop stops when Peek returns an error,
883 // which it does when r's buffer has been filled.
884 buf, err := r.Peek(peekSize)
885 if bytes.HasSuffix(buf, doubleCRLF) {
895 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
897 func (b *body) readTrailer() error {
898 // The common case, since nobody uses trailers.
899 buf, err := b.r.Peek(2)
900 if bytes.Equal(buf, singleCRLF) {
911 // Make sure there's a header terminator coming up, to prevent
912 // a DoS with an unbounded size Trailer. It's not easy to
913 // slip in a LimitReader here, as textproto.NewReader requires
914 // a concrete *bufio.Reader. Also, we can't get all the way
915 // back up to our conn's LimitedReader that *might* be backing
916 // this bufio.Reader. Instead, a hack: we iteratively Peek up
917 // to the bufio.Reader's max size, looking for a double CRLF.
918 // This limits the trailer to the underlying buffer size, typically 4kB.
919 if !seeUpcomingDoubleCRLF(b.r) {
920 return errors.New("http: suspiciously long trailer after chunked body")
923 hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
930 switch rr := b.hdr.(type) {
932 mergeSetHeader(&rr.Trailer, Header(hdr))
934 mergeSetHeader(&rr.Trailer, Header(hdr))
939 func mergeSetHeader(dst *Header, src Header) {
944 for k, vv := range src {
949 // unreadDataSizeLocked returns the number of bytes of unread input.
950 // It returns -1 if unknown.
951 // b.mu must be held.
952 func (b *body) unreadDataSizeLocked() int64 {
953 if lr, ok := b.src.(*io.LimitedReader); ok {
959 func (b *body) Close() error {
968 // Already saw EOF, so no need going to look for it.
969 case b.hdr == nil && b.closing:
970 // no trailer and closing the connection next.
971 // no point in reading to EOF.
973 // Read up to maxPostHandlerReadBytes bytes of the body, looking
974 // for EOF (and trailers), so we can re-use this connection.
975 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
976 // There was a declared Content-Length, and we have more bytes remaining
977 // than our maxPostHandlerReadBytes tolerance. So, give up.
981 // Consume the body, or, which will also lead to us reading
982 // the trailer headers after the body, if present.
983 n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
987 if n == maxPostHandlerReadBytes {
992 // Fully consume the body, which will also lead to us reading
993 // the trailer headers after the body, if present.
994 _, err = io.Copy(ioutil.Discard, bodyLocked{b})
1000 func (b *body) didEarlyClose() bool {
1006 // bodyRemains reports whether future Read calls might
1008 func (b *body) bodyRemains() bool {
1014 func (b *body) registerOnHitEOF(fn func()) {
1020 // bodyLocked is a io.Reader reading from a *body when its mutex is
1022 type bodyLocked struct {
1026 func (bl bodyLocked) Read(p []byte) (n int, err error) {
1028 return 0, ErrBodyReadAfterClose
1030 return bl.b.readLocked(p)
1033 // parseContentLength trims whitespace from s and returns -1 if no value
1034 // is set, or the value if it's >= 0.
1035 func parseContentLength(cl string) (int64, error) {
1036 cl = strings.TrimSpace(cl)
1040 n, err := strconv.ParseInt(cl, 10, 64)
1041 if err != nil || n < 0 {
1042 return 0, &badStringError{"bad Content-Length", cl}
1048 // finishAsyncByteRead finishes reading the 1-byte sniff
1049 // from the ContentLength==0, Body!=nil case.
1050 type finishAsyncByteRead struct {
1054 func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1058 rres := <-fr.tw.ByteReadCh
1059 n, err = rres.n, rres.err
1066 var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))
1068 // isKnownInMemoryReader reports whether r is a type known to not
1069 // block on Read. Its caller uses this as an optional optimization to
1070 // send fewer TCP packets.
1071 func isKnownInMemoryReader(r io.Reader) bool {
1073 case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1076 if reflect.TypeOf(r) == nopCloserType {
1077 return isKnownInMemoryReader(reflect.ValueOf(r).Field(0).Interface().(io.Reader))
1082 // bufioFlushWriter is an io.Writer wrapper that flushes all writes
1083 // on its wrapped writer if it's a *bufio.Writer.
1084 type bufioFlushWriter struct{ w io.Writer }
1086 func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
1087 n, err = fw.w.Write(p)
1088 if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
1090 if ferr != nil && err == nil {