github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/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  	"reflect"
    15  	"strconv"
    16  	"strings"
    17  	"testing"
    18  )
    19  
    20  var sniffTests = []struct {
    21  	desc        string
    22  	data        []byte
    23  	contentType string
    24  }{
    25  	// Some nonsense.
    26  	{"Empty", []byte{}, "text/plain; charset=utf-8"},
    27  	{"Binary", []byte{1, 2, 3}, "application/octet-stream"},
    28  
    29  	{"HTML document #1", []byte(`<HtMl><bOdY>blah blah blah</body></html>`), "text/html; charset=utf-8"},
    30  	{"HTML document #2", []byte(`<HTML></HTML>`), "text/html; charset=utf-8"},
    31  	{"HTML document #3 (leading whitespace)", []byte(`   <!DOCTYPE HTML>...`), "text/html; charset=utf-8"},
    32  	{"HTML document #4 (leading CRLF)", []byte("\r\n<html>..."), "text/html; charset=utf-8"},
    33  
    34  	{"Plain text", []byte(`This is not HTML. It has ☃ though.`), "text/plain; charset=utf-8"},
    35  
    36  	{"XML", []byte("\n<?xml!"), "text/xml; charset=utf-8"},
    37  
    38  	// Image types.
    39  	{"GIF 87a", []byte(`GIF87a`), "image/gif"},
    40  	{"GIF 89a", []byte(`GIF89a...`), "image/gif"},
    41  
    42  	// Audio types.
    43  	{"MIDI audio", []byte("MThd\x00\x00\x00\x06\x00\x01"), "audio/midi"},
    44  	{"MP3 audio/MPEG audio", []byte("ID3\x03\x00\x00\x00\x00\x0f"), "audio/mpeg"},
    45  	{"WAV audio #1", []byte("RIFFb\xb8\x00\x00WAVEfmt \x12\x00\x00\x00\x06"), "audio/wave"},
    46  	{"WAV audio #2", []byte("RIFF,\x00\x00\x00WAVEfmt \x12\x00\x00\x00\x06"), "audio/wave"},
    47  	{"AIFF audio #1", []byte("FORM\x00\x00\x00\x00AIFFCOMM\x00\x00\x00\x12\x00\x01\x00\x00\x57\x55\x00\x10\x40\x0d\xf3\x34"), "audio/aiff"},
    48  
    49  	{"OGG audio", []byte("OggS\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x7e\x46\x00\x00\x00\x00\x00\x00\x1f\xf6\xb4\xfc\x01\x1e\x01\x76\x6f\x72"), "application/ogg"},
    50  	{"Must not match OGG", []byte("owow\x00"), "application/octet-stream"},
    51  	{"Must not match OGG", []byte("oooS\x00"), "application/octet-stream"},
    52  	{"Must not match OGG", []byte("oggS\x00"), "application/octet-stream"},
    53  
    54  	// Video types.
    55  	{"MP4 video", []byte("\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom<\x06t\xbfmdat"), "video/mp4"},
    56  	{"AVI video #1", []byte("RIFF,O\n\x00AVI LISTÀ"), "video/avi"},
    57  	{"AVI video #2", []byte("RIFF,\n\x00\x00AVI LISTÀ"), "video/avi"},
    58  }
    59  
    60  func TestDetectContentType(t *testing.T) {
    61  	for _, tt := range sniffTests {
    62  		ct := DetectContentType(tt.data)
    63  		if ct != tt.contentType {
    64  			t.Errorf("%v: DetectContentType = %q, want %q", tt.desc, ct, tt.contentType)
    65  		}
    66  	}
    67  }
    68  
    69  func TestServerContentType_h1(t *testing.T) { testServerContentType(t, h1Mode) }
    70  func TestServerContentType_h2(t *testing.T) { testServerContentType(t, h2Mode) }
    71  
    72  func testServerContentType(t *testing.T, h2 bool) {
    73  	setParallel(t)
    74  	defer afterTest(t)
    75  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
    76  		i, _ := strconv.Atoi(r.FormValue("i"))
    77  		tt := sniffTests[i]
    78  		n, err := w.Write(tt.data)
    79  		if n != len(tt.data) || err != nil {
    80  			log.Fatalf("%v: Write(%q) = %v, %v want %d, nil", tt.desc, tt.data, n, err, len(tt.data))
    81  		}
    82  	}))
    83  	defer cst.close()
    84  
    85  	for i, tt := range sniffTests {
    86  		resp, err := cst.c.Get(cst.ts.URL + "/?i=" + strconv.Itoa(i))
    87  		if err != nil {
    88  			t.Errorf("%v: %v", tt.desc, err)
    89  			continue
    90  		}
    91  		if ct := resp.Header.Get("Content-Type"); ct != tt.contentType {
    92  			t.Errorf("%v: Content-Type = %q, want %q", tt.desc, ct, tt.contentType)
    93  		}
    94  		data, err := ioutil.ReadAll(resp.Body)
    95  		if err != nil {
    96  			t.Errorf("%v: reading body: %v", tt.desc, err)
    97  		} else if !bytes.Equal(data, tt.data) {
    98  			t.Errorf("%v: data is %q, want %q", tt.desc, data, tt.data)
    99  		}
   100  		resp.Body.Close()
   101  	}
   102  }
   103  
   104  // Issue 5953: shouldn't sniff if the handler set a Content-Type header,
   105  // even if it's the empty string.
   106  func TestServerIssue5953_h1(t *testing.T) { testServerIssue5953(t, h1Mode) }
   107  func TestServerIssue5953_h2(t *testing.T) { testServerIssue5953(t, h2Mode) }
   108  func testServerIssue5953(t *testing.T, h2 bool) {
   109  	defer afterTest(t)
   110  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
   111  		w.Header()["Content-Type"] = []string{""}
   112  		fmt.Fprintf(w, "<html><head></head><body>hi</body></html>")
   113  	}))
   114  	defer cst.close()
   115  
   116  	resp, err := cst.c.Get(cst.ts.URL)
   117  	if err != nil {
   118  		t.Fatal(err)
   119  	}
   120  
   121  	got := resp.Header["Content-Type"]
   122  	want := []string{""}
   123  	if !reflect.DeepEqual(got, want) {
   124  		t.Errorf("Content-Type = %q; want %q", got, want)
   125  	}
   126  	resp.Body.Close()
   127  }
   128  
   129  func TestContentTypeWithCopy_h1(t *testing.T) { testContentTypeWithCopy(t, h1Mode) }
   130  func TestContentTypeWithCopy_h2(t *testing.T) { testContentTypeWithCopy(t, h2Mode) }
   131  func testContentTypeWithCopy(t *testing.T, h2 bool) {
   132  	defer afterTest(t)
   133  
   134  	const (
   135  		input    = "\n<html>\n\t<head>\n"
   136  		expected = "text/html; charset=utf-8"
   137  	)
   138  
   139  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
   140  		// Use io.Copy from a bytes.Buffer to trigger ReadFrom.
   141  		buf := bytes.NewBuffer([]byte(input))
   142  		n, err := io.Copy(w, buf)
   143  		if int(n) != len(input) || err != nil {
   144  			t.Errorf("io.Copy(w, %q) = %v, %v want %d, nil", input, n, err, len(input))
   145  		}
   146  	}))
   147  	defer cst.close()
   148  
   149  	resp, err := cst.c.Get(cst.ts.URL)
   150  	if err != nil {
   151  		t.Fatalf("Get: %v", err)
   152  	}
   153  	if ct := resp.Header.Get("Content-Type"); ct != expected {
   154  		t.Errorf("Content-Type = %q, want %q", ct, expected)
   155  	}
   156  	data, err := ioutil.ReadAll(resp.Body)
   157  	if err != nil {
   158  		t.Errorf("reading body: %v", err)
   159  	} else if !bytes.Equal(data, []byte(input)) {
   160  		t.Errorf("data is %q, want %q", data, input)
   161  	}
   162  	resp.Body.Close()
   163  }
   164  
   165  func TestSniffWriteSize_h1(t *testing.T) { testSniffWriteSize(t, h1Mode) }
   166  func TestSniffWriteSize_h2(t *testing.T) { testSniffWriteSize(t, h2Mode) }
   167  func testSniffWriteSize(t *testing.T, h2 bool) {
   168  	setParallel(t)
   169  	defer afterTest(t)
   170  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
   171  		size, _ := strconv.Atoi(r.FormValue("size"))
   172  		written, err := io.WriteString(w, strings.Repeat("a", size))
   173  		if err != nil {
   174  			t.Errorf("write of %d bytes: %v", size, err)
   175  			return
   176  		}
   177  		if written != size {
   178  			t.Errorf("write of %d bytes wrote %d bytes", size, written)
   179  		}
   180  	}))
   181  	defer cst.close()
   182  	for _, size := range []int{0, 1, 200, 600, 999, 1000, 1023, 1024, 512 << 10, 1 << 20} {
   183  		res, err := cst.c.Get(fmt.Sprintf("%s/?size=%d", cst.ts.URL, size))
   184  		if err != nil {
   185  			t.Fatalf("size %d: %v", size, err)
   186  		}
   187  		if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
   188  			t.Fatalf("size %d: io.Copy of body = %v", size, err)
   189  		}
   190  		if err := res.Body.Close(); err != nil {
   191  			t.Fatalf("size %d: body Close = %v", size, err)
   192  		}
   193  	}
   194  }