Commit 9c6a73e4 authored by David Symonds's avatar David Symonds

net/http: fix sniffing when using ReadFrom.

R=golang-dev, rsc, bradfitz
CC=golang-dev
https://golang.org/cl/5362046
parent e5373c01
...@@ -149,11 +149,13 @@ type writerOnly struct { ...@@ -149,11 +149,13 @@ type writerOnly struct {
} }
func (w *response) ReadFrom(src io.Reader) (n int64, err error) { func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
// Flush before checking w.chunking, as Flush will call // Call WriteHeader before checking w.chunking if it hasn't
// WriteHeader if it hasn't been called yet, and WriteHeader // been called yet, since WriteHeader is what sets w.chunking.
// is what sets w.chunking. if !w.wroteHeader {
w.Flush() w.WriteHeader(StatusOK)
}
if !w.chunking && w.bodyAllowed() && !w.needSniff { if !w.chunking && w.bodyAllowed() && !w.needSniff {
w.Flush()
if rf, ok := w.conn.rwc.(io.ReaderFrom); ok { if rf, ok := w.conn.rwc.(io.ReaderFrom); ok {
n, err = rf.ReadFrom(src) n, err = rf.ReadFrom(src)
w.written += n w.written += n
......
...@@ -6,6 +6,7 @@ package http_test ...@@ -6,6 +6,7 @@ package http_test
import ( import (
"bytes" "bytes"
"io"
"io/ioutil" "io/ioutil"
"log" "log"
. "net/http" . "net/http"
...@@ -79,3 +80,35 @@ func TestServerContentType(t *testing.T) { ...@@ -79,3 +80,35 @@ func TestServerContentType(t *testing.T) {
resp.Body.Close() resp.Body.Close()
} }
} }
func TestContentTypeWithCopy(t *testing.T) {
const (
input = "\n<html>\n\t<head>\n"
expected = "text/html; charset=utf-8"
)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
// Use io.Copy from a bytes.Buffer to trigger ReadFrom.
buf := bytes.NewBuffer([]byte(input))
n, err := io.Copy(w, buf)
if int(n) != len(input) || err != nil {
t.Fatalf("io.Copy(w, %q) = %v, %v want %d, nil", input, n, err, len(input))
}
}))
defer ts.Close()
resp, err := Get(ts.URL)
if err != nil {
t.Fatalf("Get: %v", err)
}
if ct := resp.Header.Get("Content-Type"); ct != expected {
t.Errorf("Content-Type = %q, want %q", ct, expected)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("reading body: %v", err)
} else if !bytes.Equal(data, []byte(input)) {
t.Errorf("data is %q, want %q", data, input)
}
resp.Body.Close()
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment