github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/net/http/sniff_test.go (about)

     1  // Copyright 2011 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.
     4  
     5  package http_test
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"io"
    11  	"io/ioutil"
    12  	"log"
    13  	. "net/http"
    14  	"net/http/httptest"
    15  	"reflect"
    16  	"strconv"
    17  	"strings"
    18  	"testing"
    19  )
    20  
    21  var sniffTests = []struct {
    22  	desc        string
    23  	data        []byte
    24  	contentType string
    25  }{
    26  	// Some nonsense.
    27  	{"Empty", []byte{}, "text/plain; charset=utf-8"},
    28  	{"Binary", []byte{1, 2, 3}, "application/octet-stream"},
    29  
    30  	{"HTML document #1", []byte(`<HtMl><bOdY>blah blah blah</body></html>`), "text/html; charset=utf-8"},
    31  	{"HTML document #2", []byte(`<HTML></HTML>`), "text/html; charset=utf-8"},
    32  	{"HTML document #3 (leading whitespace)", []byte(`   <!DOCTYPE HTML>...`), "text/html; charset=utf-8"},
    33  	{"HTML document #4 (leading CRLF)", []byte("\r\n<html>..."), "text/html; charset=utf-8"},
    34  
    35  	{"Plain text", []byte(`This is not HTML. It has ☃ though.`), "text/plain; charset=utf-8"},
    36  
    37  	{"XML", []byte("\n<?xml!"), "text/xml; charset=utf-8"},
    38  
    39  	// Image types.
    40  	{"GIF 87a", []byte(`GIF87a`), "image/gif"},
    41  	{"GIF 89a", []byte(`GIF89a...`), "image/gif"},
    42  
    43  	// TODO(dsymonds): Re-enable this when the spec is sorted w.r.t. MP4.
    44  	//{"MP4 video", []byte("\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom<\x06t\xbfmdat"), "video/mp4"},
    45  	//{"MP4 audio", []byte("\x00\x00\x00\x20ftypM4A \x00\x00\x00\x00M4A mp42isom\x00\x00\x00\x00"), "audio/mp4"},
    46  }
    47  
    48  func TestDetectContentType(t *testing.T) {
    49  	for _, tt := range sniffTests {
    50  		ct := DetectContentType(tt.data)
    51  		if ct != tt.contentType {
    52  			t.Errorf("%v: DetectContentType = %q, want %q", tt.desc, ct, tt.contentType)
    53  		}
    54  	}
    55  }
    56  
    57  func TestServerContentType(t *testing.T) {
    58  	defer afterTest(t)
    59  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    60  		i, _ := strconv.Atoi(r.FormValue("i"))
    61  		tt := sniffTests[i]
    62  		n, err := w.Write(tt.data)
    63  		if n != len(tt.data) || err != nil {
    64  			log.Fatalf("%v: Write(%q) = %v, %v want %d, nil", tt.desc, tt.data, n, err, len(tt.data))
    65  		}
    66  	}))
    67  	defer ts.Close()
    68  
    69  	for i, tt := range sniffTests {
    70  		resp, err := Get(ts.URL + "/?i=" + strconv.Itoa(i))
    71  		if err != nil {
    72  			t.Errorf("%v: %v", tt.desc, err)
    73  			continue
    74  		}
    75  		if ct := resp.Header.Get("Content-Type"); ct != tt.contentType {
    76  			t.Errorf("%v: Content-Type = %q, want %q", tt.desc, ct, tt.contentType)
    77  		}
    78  		data, err := ioutil.ReadAll(resp.Body)
    79  		if err != nil {
    80  			t.Errorf("%v: reading body: %v", tt.desc, err)
    81  		} else if !bytes.Equal(data, tt.data) {
    82  			t.Errorf("%v: data is %q, want %q", tt.desc, data, tt.data)
    83  		}
    84  		resp.Body.Close()
    85  	}
    86  }
    87  
    88  // Issue 5953: shouldn't sniff if the handler set a Content-Type header,
    89  // even if it's the empty string.
    90  func TestServerIssue5953(t *testing.T) {
    91  	defer afterTest(t)
    92  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    93  		w.Header()["Content-Type"] = []string{""}
    94  		fmt.Fprintf(w, "<html><head></head><body>hi</body></html>")
    95  	}))
    96  	defer ts.Close()
    97  
    98  	resp, err := Get(ts.URL)
    99  	if err != nil {
   100  		t.Fatal(err)
   101  	}
   102  
   103  	got := resp.Header["Content-Type"]
   104  	want := []string{""}
   105  	if !reflect.DeepEqual(got, want) {
   106  		t.Errorf("Content-Type = %q; want %q", got, want)
   107  	}
   108  	resp.Body.Close()
   109  }
   110  
   111  func TestContentTypeWithCopy(t *testing.T) {
   112  	defer afterTest(t)
   113  
   114  	const (
   115  		input    = "\n<html>\n\t<head>\n"
   116  		expected = "text/html; charset=utf-8"
   117  	)
   118  
   119  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
   120  		// Use io.Copy from a bytes.Buffer to trigger ReadFrom.
   121  		buf := bytes.NewBuffer([]byte(input))
   122  		n, err := io.Copy(w, buf)
   123  		if int(n) != len(input) || err != nil {
   124  			t.Errorf("io.Copy(w, %q) = %v, %v want %d, nil", input, n, err, len(input))
   125  		}
   126  	}))
   127  	defer ts.Close()
   128  
   129  	resp, err := Get(ts.URL)
   130  	if err != nil {
   131  		t.Fatalf("Get: %v", err)
   132  	}
   133  	if ct := resp.Header.Get("Content-Type"); ct != expected {
   134  		t.Errorf("Content-Type = %q, want %q", ct, expected)
   135  	}
   136  	data, err := ioutil.ReadAll(resp.Body)
   137  	if err != nil {
   138  		t.Errorf("reading body: %v", err)
   139  	} else if !bytes.Equal(data, []byte(input)) {
   140  		t.Errorf("data is %q, want %q", data, input)
   141  	}
   142  	resp.Body.Close()
   143  }
   144  
   145  func TestSniffWriteSize(t *testing.T) {
   146  	defer afterTest(t)
   147  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
   148  		size, _ := strconv.Atoi(r.FormValue("size"))
   149  		written, err := io.WriteString(w, strings.Repeat("a", size))
   150  		if err != nil {
   151  			t.Errorf("write of %d bytes: %v", size, err)
   152  			return
   153  		}
   154  		if written != size {
   155  			t.Errorf("write of %d bytes wrote %d bytes", size, written)
   156  		}
   157  	}))
   158  	defer ts.Close()
   159  	for _, size := range []int{0, 1, 200, 600, 999, 1000, 1023, 1024, 512 << 10, 1 << 20} {
   160  		res, err := Get(fmt.Sprintf("%s/?size=%d", ts.URL, size))
   161  		if err != nil {
   162  			t.Fatalf("size %d: %v", size, err)
   163  		}
   164  		if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
   165  			t.Fatalf("size %d: io.Copy of body = %v", size, err)
   166  		}
   167  		if err := res.Body.Close(); err != nil {
   168  			t.Fatalf("size %d: body Close = %v", size, err)
   169  		}
   170  	}
   171  }