// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http_test import ( "bytes" "fmt" "io" "io/ioutil" "log" . "net/http" "net/http/httptest" "strconv" "strings" "testing" ) var sniffTests = []struct { desc string data []byte contentType string }{ // Some nonsense. {"Empty", []byte{}, "text/plain; charset=utf-8"}, {"Binary", []byte{1, 2, 3}, "application/octet-stream"}, {"HTML document #1", []byte(`blah blah blah`), "text/html; charset=utf-8"}, {"HTML document #2", []byte(``), "text/html; charset=utf-8"}, {"HTML document #3 (leading whitespace)", []byte(` ...`), "text/html; charset=utf-8"}, {"HTML document #4 (leading CRLF)", []byte("\r\n..."), "text/html; charset=utf-8"}, {"Plain text", []byte(`This is not HTML. It has ☃ though.`), "text/plain; charset=utf-8"}, {"XML", []byte("\n\n\t\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.Errorf("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() } func TestSniffWriteSize(t *testing.T) { defer afterTest(t) ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { size, _ := strconv.Atoi(r.FormValue("size")) written, err := io.WriteString(w, strings.Repeat("a", size)) if err != nil { t.Errorf("write of %d bytes: %v", size, err) return } if written != size { t.Errorf("write of %d bytes wrote %d bytes", size, written) } })) defer ts.Close() for _, size := range []int{0, 1, 200, 600, 999, 1000, 1023, 1024, 512 << 10, 1 << 20} { res, err := Get(fmt.Sprintf("%s/?size=%d", ts.URL, size)) if err != nil { t.Fatalf("size %d: %v", size, err) } if _, err := io.Copy(ioutil.Discard, res.Body); err != nil { t.Fatalf("size %d: io.Copy of body = %v", size, err) } if err := res.Body.Close(); err != nil { t.Fatalf("size %d: body Close = %v", size, err) } } }