PageRenderTime 70ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/third_party/gofrontend/libgo/go/net/http/serve_test.go

http://github.com/axw/llgo
Go | 3687 lines | 3131 code | 299 blank | 257 comment | 790 complexity | c2428b0a49ec4501730cd1924f9d265b MD5 | raw file
Possible License(s): BSD-3-Clause, MIT

Large files files are truncated, but you can click here to view the full file

  1. // Copyright 2010 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. // End-to-end serving tests
  5. package http_test
  6. import (
  7. "bufio"
  8. "bytes"
  9. "crypto/tls"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "log"
  15. "math/rand"
  16. "net"
  17. . "net/http"
  18. "net/http/httptest"
  19. "net/http/httputil"
  20. "net/http/internal"
  21. "net/url"
  22. "os"
  23. "os/exec"
  24. "reflect"
  25. "runtime"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "sync/atomic"
  30. "syscall"
  31. "testing"
  32. "time"
  33. )
  34. type dummyAddr string
  35. type oneConnListener struct {
  36. conn net.Conn
  37. }
  38. func (l *oneConnListener) Accept() (c net.Conn, err error) {
  39. c = l.conn
  40. if c == nil {
  41. err = io.EOF
  42. return
  43. }
  44. err = nil
  45. l.conn = nil
  46. return
  47. }
  48. func (l *oneConnListener) Close() error {
  49. return nil
  50. }
  51. func (l *oneConnListener) Addr() net.Addr {
  52. return dummyAddr("test-address")
  53. }
  54. func (a dummyAddr) Network() string {
  55. return string(a)
  56. }
  57. func (a dummyAddr) String() string {
  58. return string(a)
  59. }
  60. type noopConn struct{}
  61. func (noopConn) LocalAddr() net.Addr { return dummyAddr("local-addr") }
  62. func (noopConn) RemoteAddr() net.Addr { return dummyAddr("remote-addr") }
  63. func (noopConn) SetDeadline(t time.Time) error { return nil }
  64. func (noopConn) SetReadDeadline(t time.Time) error { return nil }
  65. func (noopConn) SetWriteDeadline(t time.Time) error { return nil }
  66. type rwTestConn struct {
  67. io.Reader
  68. io.Writer
  69. noopConn
  70. closeFunc func() error // called if non-nil
  71. closec chan bool // else, if non-nil, send value to it on close
  72. }
  73. func (c *rwTestConn) Close() error {
  74. if c.closeFunc != nil {
  75. return c.closeFunc()
  76. }
  77. select {
  78. case c.closec <- true:
  79. default:
  80. }
  81. return nil
  82. }
  83. type testConn struct {
  84. readBuf bytes.Buffer
  85. writeBuf bytes.Buffer
  86. closec chan bool // if non-nil, send value to it on close
  87. noopConn
  88. }
  89. func (c *testConn) Read(b []byte) (int, error) {
  90. return c.readBuf.Read(b)
  91. }
  92. func (c *testConn) Write(b []byte) (int, error) {
  93. return c.writeBuf.Write(b)
  94. }
  95. func (c *testConn) Close() error {
  96. select {
  97. case c.closec <- true:
  98. default:
  99. }
  100. return nil
  101. }
  102. // reqBytes treats req as a request (with \n delimiters) and returns it with \r\n delimiters,
  103. // ending in \r\n\r\n
  104. func reqBytes(req string) []byte {
  105. return []byte(strings.Replace(strings.TrimSpace(req), "\n", "\r\n", -1) + "\r\n\r\n")
  106. }
  107. type handlerTest struct {
  108. handler Handler
  109. }
  110. func newHandlerTest(h Handler) handlerTest {
  111. return handlerTest{h}
  112. }
  113. func (ht handlerTest) rawResponse(req string) string {
  114. reqb := reqBytes(req)
  115. var output bytes.Buffer
  116. conn := &rwTestConn{
  117. Reader: bytes.NewReader(reqb),
  118. Writer: &output,
  119. closec: make(chan bool, 1),
  120. }
  121. ln := &oneConnListener{conn: conn}
  122. go Serve(ln, ht.handler)
  123. <-conn.closec
  124. return output.String()
  125. }
  126. func TestConsumingBodyOnNextConn(t *testing.T) {
  127. defer afterTest(t)
  128. conn := new(testConn)
  129. for i := 0; i < 2; i++ {
  130. conn.readBuf.Write([]byte(
  131. "POST / HTTP/1.1\r\n" +
  132. "Host: test\r\n" +
  133. "Content-Length: 11\r\n" +
  134. "\r\n" +
  135. "foo=1&bar=1"))
  136. }
  137. reqNum := 0
  138. ch := make(chan *Request)
  139. servech := make(chan error)
  140. listener := &oneConnListener{conn}
  141. handler := func(res ResponseWriter, req *Request) {
  142. reqNum++
  143. ch <- req
  144. }
  145. go func() {
  146. servech <- Serve(listener, HandlerFunc(handler))
  147. }()
  148. var req *Request
  149. req = <-ch
  150. if req == nil {
  151. t.Fatal("Got nil first request.")
  152. }
  153. if req.Method != "POST" {
  154. t.Errorf("For request #1's method, got %q; expected %q",
  155. req.Method, "POST")
  156. }
  157. req = <-ch
  158. if req == nil {
  159. t.Fatal("Got nil first request.")
  160. }
  161. if req.Method != "POST" {
  162. t.Errorf("For request #2's method, got %q; expected %q",
  163. req.Method, "POST")
  164. }
  165. if serveerr := <-servech; serveerr != io.EOF {
  166. t.Errorf("Serve returned %q; expected EOF", serveerr)
  167. }
  168. }
  169. type stringHandler string
  170. func (s stringHandler) ServeHTTP(w ResponseWriter, r *Request) {
  171. w.Header().Set("Result", string(s))
  172. }
  173. var handlers = []struct {
  174. pattern string
  175. msg string
  176. }{
  177. {"/", "Default"},
  178. {"/someDir/", "someDir"},
  179. {"/#/", "hash"},
  180. {"someHost.com/someDir/", "someHost.com/someDir"},
  181. }
  182. var vtests = []struct {
  183. url string
  184. expected string
  185. }{
  186. {"http://localhost/someDir/apage", "someDir"},
  187. {"http://localhost/%23/apage", "hash"},
  188. {"http://localhost/otherDir/apage", "Default"},
  189. {"http://someHost.com/someDir/apage", "someHost.com/someDir"},
  190. {"http://otherHost.com/someDir/apage", "someDir"},
  191. {"http://otherHost.com/aDir/apage", "Default"},
  192. // redirections for trees
  193. {"http://localhost/someDir", "/someDir/"},
  194. {"http://localhost/%23", "/%23/"},
  195. {"http://someHost.com/someDir", "/someDir/"},
  196. }
  197. func TestHostHandlers(t *testing.T) {
  198. defer afterTest(t)
  199. mux := NewServeMux()
  200. for _, h := range handlers {
  201. mux.Handle(h.pattern, stringHandler(h.msg))
  202. }
  203. ts := httptest.NewServer(mux)
  204. defer ts.Close()
  205. conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  206. if err != nil {
  207. t.Fatal(err)
  208. }
  209. defer conn.Close()
  210. cc := httputil.NewClientConn(conn, nil)
  211. for _, vt := range vtests {
  212. var r *Response
  213. var req Request
  214. if req.URL, err = url.Parse(vt.url); err != nil {
  215. t.Errorf("cannot parse url: %v", err)
  216. continue
  217. }
  218. if err := cc.Write(&req); err != nil {
  219. t.Errorf("writing request: %v", err)
  220. continue
  221. }
  222. r, err := cc.Read(&req)
  223. if err != nil {
  224. t.Errorf("reading response: %v", err)
  225. continue
  226. }
  227. switch r.StatusCode {
  228. case StatusOK:
  229. s := r.Header.Get("Result")
  230. if s != vt.expected {
  231. t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected)
  232. }
  233. case StatusMovedPermanently:
  234. s := r.Header.Get("Location")
  235. if s != vt.expected {
  236. t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected)
  237. }
  238. default:
  239. t.Errorf("Get(%q) unhandled status code %d", vt.url, r.StatusCode)
  240. }
  241. }
  242. }
  243. var serveMuxRegister = []struct {
  244. pattern string
  245. h Handler
  246. }{
  247. {"/dir/", serve(200)},
  248. {"/search", serve(201)},
  249. {"codesearch.google.com/search", serve(202)},
  250. {"codesearch.google.com/", serve(203)},
  251. {"example.com/", HandlerFunc(checkQueryStringHandler)},
  252. }
  253. // serve returns a handler that sends a response with the given code.
  254. func serve(code int) HandlerFunc {
  255. return func(w ResponseWriter, r *Request) {
  256. w.WriteHeader(code)
  257. }
  258. }
  259. // checkQueryStringHandler checks if r.URL.RawQuery has the same value
  260. // as the URL excluding the scheme and the query string and sends 200
  261. // response code if it is, 500 otherwise.
  262. func checkQueryStringHandler(w ResponseWriter, r *Request) {
  263. u := *r.URL
  264. u.Scheme = "http"
  265. u.Host = r.Host
  266. u.RawQuery = ""
  267. if "http://"+r.URL.RawQuery == u.String() {
  268. w.WriteHeader(200)
  269. } else {
  270. w.WriteHeader(500)
  271. }
  272. }
  273. var serveMuxTests = []struct {
  274. method string
  275. host string
  276. path string
  277. code int
  278. pattern string
  279. }{
  280. {"GET", "google.com", "/", 404, ""},
  281. {"GET", "google.com", "/dir", 301, "/dir/"},
  282. {"GET", "google.com", "/dir/", 200, "/dir/"},
  283. {"GET", "google.com", "/dir/file", 200, "/dir/"},
  284. {"GET", "google.com", "/search", 201, "/search"},
  285. {"GET", "google.com", "/search/", 404, ""},
  286. {"GET", "google.com", "/search/foo", 404, ""},
  287. {"GET", "codesearch.google.com", "/search", 202, "codesearch.google.com/search"},
  288. {"GET", "codesearch.google.com", "/search/", 203, "codesearch.google.com/"},
  289. {"GET", "codesearch.google.com", "/search/foo", 203, "codesearch.google.com/"},
  290. {"GET", "codesearch.google.com", "/", 203, "codesearch.google.com/"},
  291. {"GET", "images.google.com", "/search", 201, "/search"},
  292. {"GET", "images.google.com", "/search/", 404, ""},
  293. {"GET", "images.google.com", "/search/foo", 404, ""},
  294. {"GET", "google.com", "/../search", 301, "/search"},
  295. {"GET", "google.com", "/dir/..", 301, ""},
  296. {"GET", "google.com", "/dir/..", 301, ""},
  297. {"GET", "google.com", "/dir/./file", 301, "/dir/"},
  298. // The /foo -> /foo/ redirect applies to CONNECT requests
  299. // but the path canonicalization does not.
  300. {"CONNECT", "google.com", "/dir", 301, "/dir/"},
  301. {"CONNECT", "google.com", "/../search", 404, ""},
  302. {"CONNECT", "google.com", "/dir/..", 200, "/dir/"},
  303. {"CONNECT", "google.com", "/dir/..", 200, "/dir/"},
  304. {"CONNECT", "google.com", "/dir/./file", 200, "/dir/"},
  305. }
  306. func TestServeMuxHandler(t *testing.T) {
  307. mux := NewServeMux()
  308. for _, e := range serveMuxRegister {
  309. mux.Handle(e.pattern, e.h)
  310. }
  311. for _, tt := range serveMuxTests {
  312. r := &Request{
  313. Method: tt.method,
  314. Host: tt.host,
  315. URL: &url.URL{
  316. Path: tt.path,
  317. },
  318. }
  319. h, pattern := mux.Handler(r)
  320. rr := httptest.NewRecorder()
  321. h.ServeHTTP(rr, r)
  322. if pattern != tt.pattern || rr.Code != tt.code {
  323. t.Errorf("%s %s %s = %d, %q, want %d, %q", tt.method, tt.host, tt.path, rr.Code, pattern, tt.code, tt.pattern)
  324. }
  325. }
  326. }
  327. var serveMuxTests2 = []struct {
  328. method string
  329. host string
  330. url string
  331. code int
  332. redirOk bool
  333. }{
  334. {"GET", "google.com", "/", 404, false},
  335. {"GET", "example.com", "/test/?example.com/test/", 200, false},
  336. {"GET", "example.com", "test/?example.com/test/", 200, true},
  337. }
  338. // TestServeMuxHandlerRedirects tests that automatic redirects generated by
  339. // mux.Handler() shouldn't clear the request's query string.
  340. func TestServeMuxHandlerRedirects(t *testing.T) {
  341. mux := NewServeMux()
  342. for _, e := range serveMuxRegister {
  343. mux.Handle(e.pattern, e.h)
  344. }
  345. for _, tt := range serveMuxTests2 {
  346. tries := 1
  347. turl := tt.url
  348. for tries > 0 {
  349. u, e := url.Parse(turl)
  350. if e != nil {
  351. t.Fatal(e)
  352. }
  353. r := &Request{
  354. Method: tt.method,
  355. Host: tt.host,
  356. URL: u,
  357. }
  358. h, _ := mux.Handler(r)
  359. rr := httptest.NewRecorder()
  360. h.ServeHTTP(rr, r)
  361. if rr.Code != 301 {
  362. if rr.Code != tt.code {
  363. t.Errorf("%s %s %s = %d, want %d", tt.method, tt.host, tt.url, rr.Code, tt.code)
  364. }
  365. break
  366. }
  367. if !tt.redirOk {
  368. t.Errorf("%s %s %s, unexpected redirect", tt.method, tt.host, tt.url)
  369. break
  370. }
  371. turl = rr.HeaderMap.Get("Location")
  372. tries--
  373. }
  374. if tries < 0 {
  375. t.Errorf("%s %s %s, too many redirects", tt.method, tt.host, tt.url)
  376. }
  377. }
  378. }
  379. // Tests for https://golang.org/issue/900
  380. func TestMuxRedirectLeadingSlashes(t *testing.T) {
  381. paths := []string{"//foo.txt", "///foo.txt", "/../../foo.txt"}
  382. for _, path := range paths {
  383. req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET " + path + " HTTP/1.1\r\nHost: test\r\n\r\n")))
  384. if err != nil {
  385. t.Errorf("%s", err)
  386. }
  387. mux := NewServeMux()
  388. resp := httptest.NewRecorder()
  389. mux.ServeHTTP(resp, req)
  390. if loc, expected := resp.Header().Get("Location"), "/foo.txt"; loc != expected {
  391. t.Errorf("Expected Location header set to %q; got %q", expected, loc)
  392. return
  393. }
  394. if code, expected := resp.Code, StatusMovedPermanently; code != expected {
  395. t.Errorf("Expected response code of StatusMovedPermanently; got %d", code)
  396. return
  397. }
  398. }
  399. }
  400. func TestServerTimeouts(t *testing.T) {
  401. if runtime.GOOS == "plan9" {
  402. t.Skip("skipping test; see https://golang.org/issue/7237")
  403. }
  404. defer afterTest(t)
  405. reqNum := 0
  406. ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {
  407. reqNum++
  408. fmt.Fprintf(res, "req=%d", reqNum)
  409. }))
  410. ts.Config.ReadTimeout = 250 * time.Millisecond
  411. ts.Config.WriteTimeout = 250 * time.Millisecond
  412. ts.Start()
  413. defer ts.Close()
  414. // Hit the HTTP server successfully.
  415. tr := &Transport{DisableKeepAlives: true} // they interfere with this test
  416. defer tr.CloseIdleConnections()
  417. c := &Client{Transport: tr}
  418. r, err := c.Get(ts.URL)
  419. if err != nil {
  420. t.Fatalf("http Get #1: %v", err)
  421. }
  422. got, _ := ioutil.ReadAll(r.Body)
  423. expected := "req=1"
  424. if string(got) != expected {
  425. t.Errorf("Unexpected response for request #1; got %q; expected %q",
  426. string(got), expected)
  427. }
  428. // Slow client that should timeout.
  429. t1 := time.Now()
  430. conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  431. if err != nil {
  432. t.Fatalf("Dial: %v", err)
  433. }
  434. buf := make([]byte, 1)
  435. n, err := conn.Read(buf)
  436. latency := time.Since(t1)
  437. if n != 0 || err != io.EOF {
  438. t.Errorf("Read = %v, %v, wanted %v, %v", n, err, 0, io.EOF)
  439. }
  440. if latency < 200*time.Millisecond /* fudge from 250 ms above */ {
  441. t.Errorf("got EOF after %s, want >= %s", latency, 200*time.Millisecond)
  442. }
  443. // Hit the HTTP server successfully again, verifying that the
  444. // previous slow connection didn't run our handler. (that we
  445. // get "req=2", not "req=3")
  446. r, err = Get(ts.URL)
  447. if err != nil {
  448. t.Fatalf("http Get #2: %v", err)
  449. }
  450. got, _ = ioutil.ReadAll(r.Body)
  451. expected = "req=2"
  452. if string(got) != expected {
  453. t.Errorf("Get #2 got %q, want %q", string(got), expected)
  454. }
  455. if !testing.Short() {
  456. conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  457. if err != nil {
  458. t.Fatalf("Dial: %v", err)
  459. }
  460. defer conn.Close()
  461. go io.Copy(ioutil.Discard, conn)
  462. for i := 0; i < 5; i++ {
  463. _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"))
  464. if err != nil {
  465. t.Fatalf("on write %d: %v", i, err)
  466. }
  467. time.Sleep(ts.Config.ReadTimeout / 2)
  468. }
  469. }
  470. }
  471. // golang.org/issue/4741 -- setting only a write timeout that triggers
  472. // shouldn't cause a handler to block forever on reads (next HTTP
  473. // request) that will never happen.
  474. func TestOnlyWriteTimeout(t *testing.T) {
  475. if runtime.GOOS == "plan9" {
  476. t.Skip("skipping test; see https://golang.org/issue/7237")
  477. }
  478. defer afterTest(t)
  479. var conn net.Conn
  480. var afterTimeoutErrc = make(chan error, 1)
  481. ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, req *Request) {
  482. buf := make([]byte, 512<<10)
  483. _, err := w.Write(buf)
  484. if err != nil {
  485. t.Errorf("handler Write error: %v", err)
  486. return
  487. }
  488. conn.SetWriteDeadline(time.Now().Add(-30 * time.Second))
  489. _, err = w.Write(buf)
  490. afterTimeoutErrc <- err
  491. }))
  492. ts.Listener = trackLastConnListener{ts.Listener, &conn}
  493. ts.Start()
  494. defer ts.Close()
  495. tr := &Transport{DisableKeepAlives: false}
  496. defer tr.CloseIdleConnections()
  497. c := &Client{Transport: tr}
  498. errc := make(chan error)
  499. go func() {
  500. res, err := c.Get(ts.URL)
  501. if err != nil {
  502. errc <- err
  503. return
  504. }
  505. _, err = io.Copy(ioutil.Discard, res.Body)
  506. errc <- err
  507. }()
  508. select {
  509. case err := <-errc:
  510. if err == nil {
  511. t.Errorf("expected an error from Get request")
  512. }
  513. case <-time.After(5 * time.Second):
  514. t.Fatal("timeout waiting for Get error")
  515. }
  516. if err := <-afterTimeoutErrc; err == nil {
  517. t.Error("expected write error after timeout")
  518. }
  519. }
  520. // trackLastConnListener tracks the last net.Conn that was accepted.
  521. type trackLastConnListener struct {
  522. net.Listener
  523. last *net.Conn // destination
  524. }
  525. func (l trackLastConnListener) Accept() (c net.Conn, err error) {
  526. c, err = l.Listener.Accept()
  527. *l.last = c
  528. return
  529. }
  530. // TestIdentityResponse verifies that a handler can unset
  531. func TestIdentityResponse(t *testing.T) {
  532. defer afterTest(t)
  533. handler := HandlerFunc(func(rw ResponseWriter, req *Request) {
  534. rw.Header().Set("Content-Length", "3")
  535. rw.Header().Set("Transfer-Encoding", req.FormValue("te"))
  536. switch {
  537. case req.FormValue("overwrite") == "1":
  538. _, err := rw.Write([]byte("foo TOO LONG"))
  539. if err != ErrContentLength {
  540. t.Errorf("expected ErrContentLength; got %v", err)
  541. }
  542. case req.FormValue("underwrite") == "1":
  543. rw.Header().Set("Content-Length", "500")
  544. rw.Write([]byte("too short"))
  545. default:
  546. rw.Write([]byte("foo"))
  547. }
  548. })
  549. ts := httptest.NewServer(handler)
  550. defer ts.Close()
  551. // Note: this relies on the assumption (which is true) that
  552. // Get sends HTTP/1.1 or greater requests. Otherwise the
  553. // server wouldn't have the choice to send back chunked
  554. // responses.
  555. for _, te := range []string{"", "identity"} {
  556. url := ts.URL + "/?te=" + te
  557. res, err := Get(url)
  558. if err != nil {
  559. t.Fatalf("error with Get of %s: %v", url, err)
  560. }
  561. if cl, expected := res.ContentLength, int64(3); cl != expected {
  562. t.Errorf("for %s expected res.ContentLength of %d; got %d", url, expected, cl)
  563. }
  564. if cl, expected := res.Header.Get("Content-Length"), "3"; cl != expected {
  565. t.Errorf("for %s expected Content-Length header of %q; got %q", url, expected, cl)
  566. }
  567. if tl, expected := len(res.TransferEncoding), 0; tl != expected {
  568. t.Errorf("for %s expected len(res.TransferEncoding) of %d; got %d (%v)",
  569. url, expected, tl, res.TransferEncoding)
  570. }
  571. res.Body.Close()
  572. }
  573. // Verify that ErrContentLength is returned
  574. url := ts.URL + "/?overwrite=1"
  575. res, err := Get(url)
  576. if err != nil {
  577. t.Fatalf("error with Get of %s: %v", url, err)
  578. }
  579. res.Body.Close()
  580. // Verify that the connection is closed when the declared Content-Length
  581. // is larger than what the handler wrote.
  582. conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  583. if err != nil {
  584. t.Fatalf("error dialing: %v", err)
  585. }
  586. _, err = conn.Write([]byte("GET /?underwrite=1 HTTP/1.1\r\nHost: foo\r\n\r\n"))
  587. if err != nil {
  588. t.Fatalf("error writing: %v", err)
  589. }
  590. // The ReadAll will hang for a failing test, so use a Timer to
  591. // fail explicitly.
  592. goTimeout(t, 2*time.Second, func() {
  593. got, _ := ioutil.ReadAll(conn)
  594. expectedSuffix := "\r\n\r\ntoo short"
  595. if !strings.HasSuffix(string(got), expectedSuffix) {
  596. t.Errorf("Expected output to end with %q; got response body %q",
  597. expectedSuffix, string(got))
  598. }
  599. })
  600. }
  601. func testTCPConnectionCloses(t *testing.T, req string, h Handler) {
  602. defer afterTest(t)
  603. s := httptest.NewServer(h)
  604. defer s.Close()
  605. conn, err := net.Dial("tcp", s.Listener.Addr().String())
  606. if err != nil {
  607. t.Fatal("dial error:", err)
  608. }
  609. defer conn.Close()
  610. _, err = fmt.Fprint(conn, req)
  611. if err != nil {
  612. t.Fatal("print error:", err)
  613. }
  614. r := bufio.NewReader(conn)
  615. res, err := ReadResponse(r, &Request{Method: "GET"})
  616. if err != nil {
  617. t.Fatal("ReadResponse error:", err)
  618. }
  619. didReadAll := make(chan bool, 1)
  620. go func() {
  621. select {
  622. case <-time.After(5 * time.Second):
  623. t.Error("body not closed after 5s")
  624. return
  625. case <-didReadAll:
  626. }
  627. }()
  628. _, err = ioutil.ReadAll(r)
  629. if err != nil {
  630. t.Fatal("read error:", err)
  631. }
  632. didReadAll <- true
  633. if !res.Close {
  634. t.Errorf("Response.Close = false; want true")
  635. }
  636. }
  637. // TestServeHTTP10Close verifies that HTTP/1.0 requests won't be kept alive.
  638. func TestServeHTTP10Close(t *testing.T) {
  639. testTCPConnectionCloses(t, "GET / HTTP/1.0\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
  640. ServeFile(w, r, "testdata/file")
  641. }))
  642. }
  643. // TestClientCanClose verifies that clients can also force a connection to close.
  644. func TestClientCanClose(t *testing.T) {
  645. testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nConnection: close\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
  646. // Nothing.
  647. }))
  648. }
  649. // TestHandlersCanSetConnectionClose verifies that handlers can force a connection to close,
  650. // even for HTTP/1.1 requests.
  651. func TestHandlersCanSetConnectionClose11(t *testing.T) {
  652. testTCPConnectionCloses(t, "GET / HTTP/1.1\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
  653. w.Header().Set("Connection", "close")
  654. }))
  655. }
  656. func TestHandlersCanSetConnectionClose10(t *testing.T) {
  657. testTCPConnectionCloses(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
  658. w.Header().Set("Connection", "close")
  659. }))
  660. }
  661. func TestSetsRemoteAddr(t *testing.T) {
  662. defer afterTest(t)
  663. ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  664. fmt.Fprintf(w, "%s", r.RemoteAddr)
  665. }))
  666. defer ts.Close()
  667. res, err := Get(ts.URL)
  668. if err != nil {
  669. t.Fatalf("Get error: %v", err)
  670. }
  671. body, err := ioutil.ReadAll(res.Body)
  672. if err != nil {
  673. t.Fatalf("ReadAll error: %v", err)
  674. }
  675. ip := string(body)
  676. if !strings.HasPrefix(ip, "127.0.0.1:") && !strings.HasPrefix(ip, "[::1]:") {
  677. t.Fatalf("Expected local addr; got %q", ip)
  678. }
  679. }
  680. func TestChunkedResponseHeaders(t *testing.T) {
  681. defer afterTest(t)
  682. log.SetOutput(ioutil.Discard) // is noisy otherwise
  683. defer log.SetOutput(os.Stderr)
  684. ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  685. w.Header().Set("Content-Length", "intentional gibberish") // we check that this is deleted
  686. w.(Flusher).Flush()
  687. fmt.Fprintf(w, "I am a chunked response.")
  688. }))
  689. defer ts.Close()
  690. res, err := Get(ts.URL)
  691. if err != nil {
  692. t.Fatalf("Get error: %v", err)
  693. }
  694. defer res.Body.Close()
  695. if g, e := res.ContentLength, int64(-1); g != e {
  696. t.Errorf("expected ContentLength of %d; got %d", e, g)
  697. }
  698. if g, e := res.TransferEncoding, []string{"chunked"}; !reflect.DeepEqual(g, e) {
  699. t.Errorf("expected TransferEncoding of %v; got %v", e, g)
  700. }
  701. if _, haveCL := res.Header["Content-Length"]; haveCL {
  702. t.Errorf("Unexpected Content-Length")
  703. }
  704. }
  705. func TestIdentityResponseHeaders(t *testing.T) {
  706. defer afterTest(t)
  707. log.SetOutput(ioutil.Discard) // is noisy otherwise
  708. defer log.SetOutput(os.Stderr)
  709. ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  710. w.Header().Set("Transfer-Encoding", "identity")
  711. w.(Flusher).Flush()
  712. fmt.Fprintf(w, "I am an identity response.")
  713. }))
  714. defer ts.Close()
  715. res, err := Get(ts.URL)
  716. if err != nil {
  717. t.Fatalf("Get error: %v", err)
  718. }
  719. defer res.Body.Close()
  720. if g, e := res.TransferEncoding, []string(nil); !reflect.DeepEqual(g, e) {
  721. t.Errorf("expected TransferEncoding of %v; got %v", e, g)
  722. }
  723. if _, haveCL := res.Header["Content-Length"]; haveCL {
  724. t.Errorf("Unexpected Content-Length")
  725. }
  726. if !res.Close {
  727. t.Errorf("expected Connection: close; got %v", res.Close)
  728. }
  729. }
  730. // Test304Responses verifies that 304s don't declare that they're
  731. // chunking in their response headers and aren't allowed to produce
  732. // output.
  733. func Test304Responses(t *testing.T) {
  734. defer afterTest(t)
  735. ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  736. w.WriteHeader(StatusNotModified)
  737. _, err := w.Write([]byte("illegal body"))
  738. if err != ErrBodyNotAllowed {
  739. t.Errorf("on Write, expected ErrBodyNotAllowed, got %v", err)
  740. }
  741. }))
  742. defer ts.Close()
  743. res, err := Get(ts.URL)
  744. if err != nil {
  745. t.Error(err)
  746. }
  747. if len(res.TransferEncoding) > 0 {
  748. t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding)
  749. }
  750. body, err := ioutil.ReadAll(res.Body)
  751. if err != nil {
  752. t.Error(err)
  753. }
  754. if len(body) > 0 {
  755. t.Errorf("got unexpected body %q", string(body))
  756. }
  757. }
  758. // TestHeadResponses verifies that all MIME type sniffing and Content-Length
  759. // counting of GET requests also happens on HEAD requests.
  760. func TestHeadResponses(t *testing.T) {
  761. defer afterTest(t)
  762. ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  763. _, err := w.Write([]byte("<html>"))
  764. if err != nil {
  765. t.Errorf("ResponseWriter.Write: %v", err)
  766. }
  767. // Also exercise the ReaderFrom path
  768. _, err = io.Copy(w, strings.NewReader("789a"))
  769. if err != nil {
  770. t.Errorf("Copy(ResponseWriter, ...): %v", err)
  771. }
  772. }))
  773. defer ts.Close()
  774. res, err := Head(ts.URL)
  775. if err != nil {
  776. t.Error(err)
  777. }
  778. if len(res.TransferEncoding) > 0 {
  779. t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding)
  780. }
  781. if ct := res.Header.Get("Content-Type"); ct != "text/html; charset=utf-8" {
  782. t.Errorf("Content-Type: %q; want text/html; charset=utf-8", ct)
  783. }
  784. if v := res.ContentLength; v != 10 {
  785. t.Errorf("Content-Length: %d; want 10", v)
  786. }
  787. body, err := ioutil.ReadAll(res.Body)
  788. if err != nil {
  789. t.Error(err)
  790. }
  791. if len(body) > 0 {
  792. t.Errorf("got unexpected body %q", string(body))
  793. }
  794. }
  795. func TestTLSHandshakeTimeout(t *testing.T) {
  796. if runtime.GOOS == "plan9" {
  797. t.Skip("skipping test; see https://golang.org/issue/7237")
  798. }
  799. defer afterTest(t)
  800. ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
  801. errc := make(chanWriter, 10) // but only expecting 1
  802. ts.Config.ReadTimeout = 250 * time.Millisecond
  803. ts.Config.ErrorLog = log.New(errc, "", 0)
  804. ts.StartTLS()
  805. defer ts.Close()
  806. conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  807. if err != nil {
  808. t.Fatalf("Dial: %v", err)
  809. }
  810. defer conn.Close()
  811. goTimeout(t, 10*time.Second, func() {
  812. var buf [1]byte
  813. n, err := conn.Read(buf[:])
  814. if err == nil || n != 0 {
  815. t.Errorf("Read = %d, %v; want an error and no bytes", n, err)
  816. }
  817. })
  818. select {
  819. case v := <-errc:
  820. if !strings.Contains(v, "timeout") && !strings.Contains(v, "TLS handshake") {
  821. t.Errorf("expected a TLS handshake timeout error; got %q", v)
  822. }
  823. case <-time.After(5 * time.Second):
  824. t.Errorf("timeout waiting for logged error")
  825. }
  826. }
  827. func TestTLSServer(t *testing.T) {
  828. defer afterTest(t)
  829. ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  830. if r.TLS != nil {
  831. w.Header().Set("X-TLS-Set", "true")
  832. if r.TLS.HandshakeComplete {
  833. w.Header().Set("X-TLS-HandshakeComplete", "true")
  834. }
  835. }
  836. }))
  837. ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
  838. defer ts.Close()
  839. // Connect an idle TCP connection to this server before we run
  840. // our real tests. This idle connection used to block forever
  841. // in the TLS handshake, preventing future connections from
  842. // being accepted. It may prevent future accidental blocking
  843. // in newConn.
  844. idleConn, err := net.Dial("tcp", ts.Listener.Addr().String())
  845. if err != nil {
  846. t.Fatalf("Dial: %v", err)
  847. }
  848. defer idleConn.Close()
  849. goTimeout(t, 10*time.Second, func() {
  850. if !strings.HasPrefix(ts.URL, "https://") {
  851. t.Errorf("expected test TLS server to start with https://, got %q", ts.URL)
  852. return
  853. }
  854. noVerifyTransport := &Transport{
  855. TLSClientConfig: &tls.Config{
  856. InsecureSkipVerify: true,
  857. },
  858. }
  859. client := &Client{Transport: noVerifyTransport}
  860. res, err := client.Get(ts.URL)
  861. if err != nil {
  862. t.Error(err)
  863. return
  864. }
  865. if res == nil {
  866. t.Errorf("got nil Response")
  867. return
  868. }
  869. defer res.Body.Close()
  870. if res.Header.Get("X-TLS-Set") != "true" {
  871. t.Errorf("expected X-TLS-Set response header")
  872. return
  873. }
  874. if res.Header.Get("X-TLS-HandshakeComplete") != "true" {
  875. t.Errorf("expected X-TLS-HandshakeComplete header")
  876. }
  877. })
  878. }
  879. type serverExpectTest struct {
  880. contentLength int // of request body
  881. chunked bool
  882. expectation string // e.g. "100-continue"
  883. readBody bool // whether handler should read the body (if false, sends StatusUnauthorized)
  884. expectedResponse string // expected substring in first line of http response
  885. }
  886. func expectTest(contentLength int, expectation string, readBody bool, expectedResponse string) serverExpectTest {
  887. return serverExpectTest{
  888. contentLength: contentLength,
  889. expectation: expectation,
  890. readBody: readBody,
  891. expectedResponse: expectedResponse,
  892. }
  893. }
  894. var serverExpectTests = []serverExpectTest{
  895. // Normal 100-continues, case-insensitive.
  896. expectTest(100, "100-continue", true, "100 Continue"),
  897. expectTest(100, "100-cOntInUE", true, "100 Continue"),
  898. // No 100-continue.
  899. expectTest(100, "", true, "200 OK"),
  900. // 100-continue but requesting client to deny us,
  901. // so it never reads the body.
  902. expectTest(100, "100-continue", false, "401 Unauthorized"),
  903. // Likewise without 100-continue:
  904. expectTest(100, "", false, "401 Unauthorized"),
  905. // Non-standard expectations are failures
  906. expectTest(0, "a-pony", false, "417 Expectation Failed"),
  907. // Expect-100 requested but no body (is apparently okay: Issue 7625)
  908. expectTest(0, "100-continue", true, "200 OK"),
  909. // Expect-100 requested but handler doesn't read the body
  910. expectTest(0, "100-continue", false, "401 Unauthorized"),
  911. // Expect-100 continue with no body, but a chunked body.
  912. {
  913. expectation: "100-continue",
  914. readBody: true,
  915. chunked: true,
  916. expectedResponse: "100 Continue",
  917. },
  918. }
  919. // Tests that the server responds to the "Expect" request header
  920. // correctly.
  921. func TestServerExpect(t *testing.T) {
  922. defer afterTest(t)
  923. ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  924. // Note using r.FormValue("readbody") because for POST
  925. // requests that would read from r.Body, which we only
  926. // conditionally want to do.
  927. if strings.Contains(r.URL.RawQuery, "readbody=true") {
  928. ioutil.ReadAll(r.Body)
  929. w.Write([]byte("Hi"))
  930. } else {
  931. w.WriteHeader(StatusUnauthorized)
  932. }
  933. }))
  934. defer ts.Close()
  935. runTest := func(test serverExpectTest) {
  936. conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  937. if err != nil {
  938. t.Fatalf("Dial: %v", err)
  939. }
  940. defer conn.Close()
  941. // Only send the body immediately if we're acting like an HTTP client
  942. // that doesn't send 100-continue expectations.
  943. writeBody := test.contentLength != 0 && strings.ToLower(test.expectation) != "100-continue"
  944. go func() {
  945. contentLen := fmt.Sprintf("Content-Length: %d", test.contentLength)
  946. if test.chunked {
  947. contentLen = "Transfer-Encoding: chunked"
  948. }
  949. _, err := fmt.Fprintf(conn, "POST /?readbody=%v HTTP/1.1\r\n"+
  950. "Connection: close\r\n"+
  951. "%s\r\n"+
  952. "Expect: %s\r\nHost: foo\r\n\r\n",
  953. test.readBody, contentLen, test.expectation)
  954. if err != nil {
  955. t.Errorf("On test %#v, error writing request headers: %v", test, err)
  956. return
  957. }
  958. if writeBody {
  959. var targ io.WriteCloser = struct {
  960. io.Writer
  961. io.Closer
  962. }{
  963. conn,
  964. ioutil.NopCloser(nil),
  965. }
  966. if test.chunked {
  967. targ = httputil.NewChunkedWriter(conn)
  968. }
  969. body := strings.Repeat("A", test.contentLength)
  970. _, err = fmt.Fprint(targ, body)
  971. if err == nil {
  972. err = targ.Close()
  973. }
  974. if err != nil {
  975. if !test.readBody {
  976. // Server likely already hung up on us.
  977. // See larger comment below.
  978. t.Logf("On test %#v, acceptable error writing request body: %v", test, err)
  979. return
  980. }
  981. t.Errorf("On test %#v, error writing request body: %v", test, err)
  982. }
  983. }
  984. }()
  985. bufr := bufio.NewReader(conn)
  986. line, err := bufr.ReadString('\n')
  987. if err != nil {
  988. if writeBody && !test.readBody {
  989. // This is an acceptable failure due to a possible TCP race:
  990. // We were still writing data and the server hung up on us. A TCP
  991. // implementation may send a RST if our request body data was known
  992. // to be lost, which may trigger our reads to fail.
  993. // See RFC 1122 page 88.
  994. t.Logf("On test %#v, acceptable error from ReadString: %v", test, err)
  995. return
  996. }
  997. t.Fatalf("On test %#v, ReadString: %v", test, err)
  998. }
  999. if !strings.Contains(line, test.expectedResponse) {
  1000. t.Errorf("On test %#v, got first line = %q; want %q", test, line, test.expectedResponse)
  1001. }
  1002. }
  1003. for _, test := range serverExpectTests {
  1004. runTest(test)
  1005. }
  1006. }
  1007. // Under a ~256KB (maxPostHandlerReadBytes) threshold, the server
  1008. // should consume client request bodies that a handler didn't read.
  1009. func TestServerUnreadRequestBodyLittle(t *testing.T) {
  1010. defer afterTest(t)
  1011. conn := new(testConn)
  1012. body := strings.Repeat("x", 100<<10)
  1013. conn.readBuf.Write([]byte(fmt.Sprintf(
  1014. "POST / HTTP/1.1\r\n"+
  1015. "Host: test\r\n"+
  1016. "Content-Length: %d\r\n"+
  1017. "\r\n", len(body))))
  1018. conn.readBuf.Write([]byte(body))
  1019. done := make(chan bool)
  1020. ls := &oneConnListener{conn}
  1021. go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  1022. defer close(done)
  1023. if conn.readBuf.Len() < len(body)/2 {
  1024. t.Errorf("on request, read buffer length is %d; expected about 100 KB", conn.readBuf.Len())
  1025. }
  1026. rw.WriteHeader(200)
  1027. rw.(Flusher).Flush()
  1028. if g, e := conn.readBuf.Len(), 0; g != e {
  1029. t.Errorf("after WriteHeader, read buffer length is %d; want %d", g, e)
  1030. }
  1031. if c := rw.Header().Get("Connection"); c != "" {
  1032. t.Errorf(`Connection header = %q; want ""`, c)
  1033. }
  1034. }))
  1035. <-done
  1036. }
  1037. // Over a ~256KB (maxPostHandlerReadBytes) threshold, the server
  1038. // should ignore client request bodies that a handler didn't read
  1039. // and close the connection.
  1040. func TestServerUnreadRequestBodyLarge(t *testing.T) {
  1041. conn := new(testConn)
  1042. body := strings.Repeat("x", 1<<20)
  1043. conn.readBuf.Write([]byte(fmt.Sprintf(
  1044. "POST / HTTP/1.1\r\n"+
  1045. "Host: test\r\n"+
  1046. "Content-Length: %d\r\n"+
  1047. "\r\n", len(body))))
  1048. conn.readBuf.Write([]byte(body))
  1049. conn.closec = make(chan bool, 1)
  1050. ls := &oneConnListener{conn}
  1051. go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  1052. if conn.readBuf.Len() < len(body)/2 {
  1053. t.Errorf("on request, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
  1054. }
  1055. rw.WriteHeader(200)
  1056. rw.(Flusher).Flush()
  1057. if conn.readBuf.Len() < len(body)/2 {
  1058. t.Errorf("post-WriteHeader, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
  1059. }
  1060. }))
  1061. <-conn.closec
  1062. if res := conn.writeBuf.String(); !strings.Contains(res, "Connection: close") {
  1063. t.Errorf("Expected a Connection: close header; got response: %s", res)
  1064. }
  1065. }
  1066. type handlerBodyCloseTest struct {
  1067. bodySize int
  1068. bodyChunked bool
  1069. reqConnClose bool
  1070. wantEOFSearch bool // should Handler's Body.Close do Reads, looking for EOF?
  1071. wantNextReq bool // should it find the next request on the same conn?
  1072. }
  1073. func (t handlerBodyCloseTest) connectionHeader() string {
  1074. if t.reqConnClose {
  1075. return "Connection: close\r\n"
  1076. }
  1077. return ""
  1078. }
  1079. var handlerBodyCloseTests = [...]handlerBodyCloseTest{
  1080. // Small enough to slurp past to the next request +
  1081. // has Content-Length.
  1082. 0: {
  1083. bodySize: 20 << 10,
  1084. bodyChunked: false,
  1085. reqConnClose: false,
  1086. wantEOFSearch: true,
  1087. wantNextReq: true,
  1088. },
  1089. // Small enough to slurp past to the next request +
  1090. // is chunked.
  1091. 1: {
  1092. bodySize: 20 << 10,
  1093. bodyChunked: true,
  1094. reqConnClose: false,
  1095. wantEOFSearch: true,
  1096. wantNextReq: true,
  1097. },
  1098. // Small enough to slurp past to the next request +
  1099. // has Content-Length +
  1100. // declares Connection: close (so pointless to read more).
  1101. 2: {
  1102. bodySize: 20 << 10,
  1103. bodyChunked: false,
  1104. reqConnClose: true,
  1105. wantEOFSearch: false,
  1106. wantNextReq: false,
  1107. },
  1108. // Small enough to slurp past to the next request +
  1109. // declares Connection: close,
  1110. // but chunked, so it might have trailers.
  1111. // TODO: maybe skip this search if no trailers were declared
  1112. // in the headers.
  1113. 3: {
  1114. bodySize: 20 << 10,
  1115. bodyChunked: true,
  1116. reqConnClose: true,
  1117. wantEOFSearch: true,
  1118. wantNextReq: false,
  1119. },
  1120. // Big with Content-Length, so give up immediately if we know it's too big.
  1121. 4: {
  1122. bodySize: 1 << 20,
  1123. bodyChunked: false, // has a Content-Length
  1124. reqConnClose: false,
  1125. wantEOFSearch: false,
  1126. wantNextReq: false,
  1127. },
  1128. // Big chunked, so read a bit before giving up.
  1129. 5: {
  1130. bodySize: 1 << 20,
  1131. bodyChunked: true,
  1132. reqConnClose: false,
  1133. wantEOFSearch: true,
  1134. wantNextReq: false,
  1135. },
  1136. // Big with Connection: close, but chunked, so search for trailers.
  1137. // TODO: maybe skip this search if no trailers were declared
  1138. // in the headers.
  1139. 6: {
  1140. bodySize: 1 << 20,
  1141. bodyChunked: true,
  1142. reqConnClose: true,
  1143. wantEOFSearch: true,
  1144. wantNextReq: false,
  1145. },
  1146. // Big with Connection: close, so don't do any reads on Close.
  1147. // With Content-Length.
  1148. 7: {
  1149. bodySize: 1 << 20,
  1150. bodyChunked: false,
  1151. reqConnClose: true,
  1152. wantEOFSearch: false,
  1153. wantNextReq: false,
  1154. },
  1155. }
  1156. func TestHandlerBodyClose(t *testing.T) {
  1157. for i, tt := range handlerBodyCloseTests {
  1158. testHandlerBodyClose(t, i, tt)
  1159. }
  1160. }
  1161. func testHandlerBodyClose(t *testing.T, i int, tt handlerBodyCloseTest) {
  1162. conn := new(testConn)
  1163. body := strings.Repeat("x", tt.bodySize)
  1164. if tt.bodyChunked {
  1165. conn.readBuf.WriteString("POST / HTTP/1.1\r\n" +
  1166. "Host: test\r\n" +
  1167. tt.connectionHeader() +
  1168. "Transfer-Encoding: chunked\r\n" +
  1169. "\r\n")
  1170. cw := internal.NewChunkedWriter(&conn.readBuf)
  1171. io.WriteString(cw, body)
  1172. cw.Close()
  1173. conn.readBuf.WriteString("\r\n")
  1174. } else {
  1175. conn.readBuf.Write([]byte(fmt.Sprintf(
  1176. "POST / HTTP/1.1\r\n"+
  1177. "Host: test\r\n"+
  1178. tt.connectionHeader()+
  1179. "Content-Length: %d\r\n"+
  1180. "\r\n", len(body))))
  1181. conn.readBuf.Write([]byte(body))
  1182. }
  1183. if !tt.reqConnClose {
  1184. conn.readBuf.WriteString("GET / HTTP/1.1\r\nHost: test\r\n\r\n")
  1185. }
  1186. conn.closec = make(chan bool, 1)
  1187. ls := &oneConnListener{conn}
  1188. var numReqs int
  1189. var size0, size1 int
  1190. go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  1191. numReqs++
  1192. if numReqs == 1 {
  1193. size0 = conn.readBuf.Len()
  1194. req.Body.Close()
  1195. size1 = conn.readBuf.Len()
  1196. }
  1197. }))
  1198. <-conn.closec
  1199. if numReqs < 1 || numReqs > 2 {
  1200. t.Fatalf("%d. bug in test. unexpected number of requests = %d", i, numReqs)
  1201. }
  1202. didSearch := size0 != size1
  1203. if didSearch != tt.wantEOFSearch {
  1204. t.Errorf("%d. did EOF search = %v; want %v (size went from %d to %d)", i, didSearch, !didSearch, size0, size1)
  1205. }
  1206. if tt.wantNextReq && numReqs != 2 {
  1207. t.Errorf("%d. numReq = %d; want 2", i, numReqs)
  1208. }
  1209. }
  1210. // testHandlerBodyConsumer represents a function injected into a test handler to
  1211. // vary work done on a request Body.
  1212. type testHandlerBodyConsumer struct {
  1213. name string
  1214. f func(io.ReadCloser)
  1215. }
  1216. var testHandlerBodyConsumers = []testHandlerBodyConsumer{
  1217. {"nil", func(io.ReadCloser) {}},
  1218. {"close", func(r io.ReadCloser) { r.Close() }},
  1219. {"discard", func(r io.ReadCloser) { io.Copy(ioutil.Discard, r) }},
  1220. }
  1221. func TestRequestBodyReadErrorClosesConnection(t *testing.T) {
  1222. defer afterTest(t)
  1223. for _, handler := range testHandlerBodyConsumers {
  1224. conn := new(testConn)
  1225. conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
  1226. "Host: test\r\n" +
  1227. "Transfer-Encoding: chunked\r\n" +
  1228. "\r\n" +
  1229. "hax\r\n" + // Invalid chunked encoding
  1230. "GET /secret HTTP/1.1\r\n" +
  1231. "Host: test\r\n" +
  1232. "\r\n")
  1233. conn.closec = make(chan bool, 1)
  1234. ls := &oneConnListener{conn}
  1235. var numReqs int
  1236. go Serve(ls, HandlerFunc(func(_ ResponseWriter, req *Request) {
  1237. numReqs++
  1238. if strings.Contains(req.URL.Path, "secret") {
  1239. t.Error("Request for /secret encountered, should not have happened.")
  1240. }
  1241. handler.f(req.Body)
  1242. }))
  1243. <-conn.closec
  1244. if numReqs != 1 {
  1245. t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
  1246. }
  1247. }
  1248. }
  1249. func TestInvalidTrailerClosesConnection(t *testing.T) {
  1250. defer afterTest(t)
  1251. for _, handler := range testHandlerBodyConsumers {
  1252. conn := new(testConn)
  1253. conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
  1254. "Host: test\r\n" +
  1255. "Trailer: hack\r\n" +
  1256. "Transfer-Encoding: chunked\r\n" +
  1257. "\r\n" +
  1258. "3\r\n" +
  1259. "hax\r\n" +
  1260. "0\r\n" +
  1261. "I'm not a valid trailer\r\n" +
  1262. "GET /secret HTTP/1.1\r\n" +
  1263. "Host: test\r\n" +
  1264. "\r\n")
  1265. conn.closec = make(chan bool, 1)
  1266. ln := &oneConnListener{conn}
  1267. var numReqs int
  1268. go Serve(ln, HandlerFunc(func(_ ResponseWriter, req *Request) {
  1269. numReqs++
  1270. if strings.Contains(req.URL.Path, "secret") {
  1271. t.Errorf("Handler %s, Request for /secret encountered, should not have happened.", handler.name)
  1272. }
  1273. handler.f(req.Body)
  1274. }))
  1275. <-conn.closec
  1276. if numReqs != 1 {
  1277. t.Errorf("Handler %s: got %d reqs; want 1", handler.name, numReqs)
  1278. }
  1279. }
  1280. }
  1281. // slowTestConn is a net.Conn that provides a means to simulate parts of a
  1282. // request being received piecemeal. Deadlines can be set and enforced in both
  1283. // Read and Write.
  1284. type slowTestConn struct {
  1285. // over multiple calls to Read, time.Durations are slept, strings are read.
  1286. script []interface{}
  1287. closec chan bool
  1288. rd, wd time.Time // read, write deadline
  1289. noopConn
  1290. }
  1291. func (c *slowTestConn) SetDeadline(t time.Time) error {
  1292. c.SetReadDeadline(t)
  1293. c.SetWriteDeadline(t)
  1294. return nil
  1295. }
  1296. func (c *slowTestConn) SetReadDeadline(t time.Time) error {
  1297. c.rd = t
  1298. return nil
  1299. }
  1300. func (c *slowTestConn) SetWriteDeadline(t time.Time) error {
  1301. c.wd = t
  1302. return nil
  1303. }
  1304. func (c *slowTestConn) Read(b []byte) (n int, err error) {
  1305. restart:
  1306. if !c.rd.IsZero() && time.Now().After(c.rd) {
  1307. return 0, syscall.ETIMEDOUT
  1308. }
  1309. if len(c.script) == 0 {
  1310. return 0, io.EOF
  1311. }
  1312. switch cue := c.script[0].(type) {
  1313. case time.Duration:
  1314. if !c.rd.IsZero() {
  1315. // If the deadline falls in the middle of our sleep window, deduct
  1316. // part of the sleep, then return a timeout.
  1317. if remaining := c.rd.Sub(time.Now()); remaining < cue {
  1318. c.script[0] = cue - remaining
  1319. time.Sleep(remaining)
  1320. return 0, syscall.ETIMEDOUT
  1321. }
  1322. }
  1323. c.script = c.script[1:]
  1324. time.Sleep(cue)
  1325. goto restart
  1326. case string:
  1327. n = copy(b, cue)
  1328. // If cue is too big for the buffer, leave the end for the next Read.
  1329. if len(cue) > n {
  1330. c.script[0] = cue[n:]
  1331. } else {
  1332. c.script = c.script[1:]
  1333. }
  1334. default:
  1335. panic("unknown cue in slowTestConn script")
  1336. }
  1337. return
  1338. }
  1339. func (c *slowTestConn) Close() error {
  1340. select {
  1341. case c.closec <- true:
  1342. default:
  1343. }
  1344. return nil
  1345. }
  1346. func (c *slowTestConn) Write(b []byte) (int, error) {
  1347. if !c.wd.IsZero() && time.Now().After(c.wd) {
  1348. return 0, syscall.ETIMEDOUT
  1349. }
  1350. return len(b), nil
  1351. }
  1352. func TestRequestBodyTimeoutClosesConnection(t *testing.T) {
  1353. if testing.Short() {
  1354. t.Skip("skipping in -short mode")
  1355. }
  1356. defer afterTest(t)
  1357. for _, handler := range testHandlerBodyConsumers {
  1358. conn := &slowTestConn{
  1359. script: []interface{}{
  1360. "POST /public HTTP/1.1\r\n" +
  1361. "Host: test\r\n" +
  1362. "Content-Length: 10000\r\n" +
  1363. "\r\n",
  1364. "foo bar baz",
  1365. 600 * time.Millisecond, // Request deadline should hit here
  1366. "GET /secret HTTP/1.1\r\n" +
  1367. "Host: test\r\n" +
  1368. "\r\n",
  1369. },
  1370. closec: make(chan bool, 1),
  1371. }
  1372. ls := &oneConnListener{conn}
  1373. var numReqs int
  1374. s := Server{
  1375. Handler: HandlerFunc(func(_ ResponseWriter, req *Request) {
  1376. numReqs++
  1377. if strings.Contains(req.URL.Path, "secret") {
  1378. t.Error("Request for /secret encountered, should not have happened.")
  1379. }
  1380. handler.f(req.Body)
  1381. }),
  1382. ReadTimeout: 400 * time.Millisecond,
  1383. }
  1384. go s.Serve(ls)
  1385. <-conn.closec
  1386. if numReqs != 1 {
  1387. t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
  1388. }
  1389. }
  1390. }
  1391. func TestTimeoutHandler(t *testing.T) {
  1392. defer afterTest(t)
  1393. sendHi := make(chan bool, 1)
  1394. writeErrors := make(chan error, 1)
  1395. sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  1396. <-sendHi
  1397. _, werr := w.Write([]byte("hi"))
  1398. writeErrors <- werr
  1399. })
  1400. timeout := make(chan time.Time, 1) // write to this to force timeouts
  1401. ts := httptest.NewServer(NewTestTimeoutHandler(sayHi, timeout))
  1402. defer ts.Close()
  1403. // Succeed without timing out:
  1404. sendHi <- true
  1405. res, err := Get(ts.URL)
  1406. if err != nil {
  1407. t.Error(err)
  1408. }
  1409. if g, e := res.StatusCode, StatusOK; g != e {
  1410. t.Errorf("got res.StatusCode %d; expected %d", g, e)
  1411. }
  1412. body, _ := ioutil.ReadAll(res.Body)
  1413. if g, e := string(body), "hi"; g != e {
  1414. t.Errorf("got body %q; expected %q", g, e)
  1415. }
  1416. if g := <-writeErrors; g != nil {
  1417. t.Errorf("got unexpected Write error on first request: %v", g)
  1418. }
  1419. // Times out:
  1420. timeout <- time.Time{}
  1421. res, err = Get(ts.URL)
  1422. if err != nil {
  1423. t.Error(err)
  1424. }
  1425. if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
  1426. t.Errorf("got res.StatusCode %d; expected %d", g, e)
  1427. }
  1428. body, _ = ioutil.ReadAll(res.Body)
  1429. if !strings.Contains(string(body), "<title>Timeout</title>") {
  1430. t.Errorf("expected timeout body; got %q", string(body))
  1431. }
  1432. // Now make the previously-timed out handler speak again,
  1433. // which verifies the panic is handled:
  1434. sendHi <- true
  1435. if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
  1436. t.Errorf("expected Write error of %v; got %v", e, g)
  1437. }
  1438. }
  1439. // See issues 8209 and 8414.
  1440. func TestTimeoutHandlerRace(t *testing.T) {
  1441. defer afterTest(t)
  1442. delayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  1443. ms, _ := strconv.Atoi(r.URL.Path[1:])
  1444. if ms == 0 {
  1445. ms = 1
  1446. }
  1447. for i := 0; i < ms; i++ {
  1448. w.Write([]byte("hi"))
  1449. time.Sleep(time.Millisecond)
  1450. }
  1451. })
  1452. ts := httptest.NewServer(TimeoutHandler(delayHi, 20*time.Millisecond, ""))
  1453. defer ts.Close()
  1454. var wg sync.WaitGroup
  1455. gate := make(chan bool, 10)
  1456. n := 50
  1457. if testing.Short() {
  1458. n = 10
  1459. gate = make(chan bool, 3)
  1460. }
  1461. for i := 0; i < n; i++ {
  1462. gate <- true
  1463. wg.Add(1)
  1464. go func() {
  1465. defer wg.Done()
  1466. defer func() { <-gate }()
  1467. res, err := Get(fmt.Sprintf("%s/%d", ts.URL, rand.Intn(50)))
  1468. if err == nil {
  1469. io.Copy(ioutil.Discard, res.Body)
  1470. res.Body.Close()
  1471. }
  1472. }()
  1473. }
  1474. wg.Wait()
  1475. }
  1476. // See issues 8209 and 8414.
  1477. func TestTimeoutHandlerRaceHeader(t *testing.T) {
  1478. defer afterTest(t)
  1479. delay204 := HandlerFunc(func(w ResponseWriter, r *Request) {
  1480. w.WriteHeader(204)
  1481. })
  1482. ts := httptest.NewServer(TimeoutHandler(delay204, time.Nanosecond, ""))
  1483. defer ts.Close()
  1484. var wg sync.WaitGroup
  1485. gate := make(chan bool, 50)
  1486. n := 500
  1487. if testing.Short() {
  1488. n = 10
  1489. }
  1490. for i := 0; i < n; i++ {
  1491. gate <- true
  1492. wg.Add(1)
  1493. go func() {
  1494. defer wg.Done()
  1495. defer func() { <-gate }()
  1496. res, err := Get(ts.URL)
  1497. if err != nil {
  1498. t.Error(err)
  1499. return
  1500. }
  1501. defer res.Body.Close()
  1502. io.Copy(ioutil.Discard, res.Body)
  1503. }()
  1504. }
  1505. wg.Wait()
  1506. }
  1507. // Verifies we don't path.Clean() on the wrong parts in redirects.
  1508. func TestRedirectMunging(t *testing.T) {
  1509. req, _ := NewRequest("GET", "http://example.com/", nil)
  1510. resp := httptest.NewRecorder()
  1511. Redirect(resp, req, "/foo?next=http://bar.com/", 302)
  1512. if g, e := resp.Header().Get("Location"), "/foo?next=http://bar.com/"; g != e {
  1513. t.Errorf("Location header was %q; want %q", g, e)
  1514. }
  1515. resp = httptest.NewRecorder()
  1516. Redirect(resp, req, "http://localhost:8080/_ah/login?continue=http://localhost:8080/", 302)
  1517. if g, e := resp.Header().Get("Location"), "http://localhost:8080/_ah/login?continue=http://localhost:8080/"; g != e {
  1518. t.Errorf("Location header was %q; want %q", g, e)
  1519. }
  1520. }
  1521. func TestRedirectBadPath(t *testing.T) {
  1522. // This used to crash. It's not valid input (bad path), but it
  1523. // shouldn't crash.
  1524. rr := httptest.NewRecorder()
  1525. req := &Request{
  1526. Method: "GET",
  1527. URL: &url.URL{
  1528. Scheme: "http",
  1529. Path: "not-empty-but-no-leading-slash", // bogus
  1530. },
  1531. }
  1532. Redirect(rr, req, "", 304)
  1533. if rr.Code != 304 {
  1534. t.Errorf("Code = %d; want 304", rr.Code)
  1535. }
  1536. }
  1537. // TestZeroLengthPostAndResponse exercises an optimization done by the Transport:
  1538. // when there is no body (either because the method doesn't permit a body, or an
  1539. // explicit Content-Length of zero is present), then the transport can re-use the
  1540. // connection immediately. But when it re-uses the connection, it typically closes
  1541. // the previous request's body, which is not optimal for zero-lengthed bodies,
  1542. // as the client would then see http.ErrBodyReadAfterClose and not 0, io.EOF.
  1543. func TestZeroLengthPostAndResponse(t *testing.T) {
  1544. defer afterTest(t)
  1545. ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  1546. all, err := ioutil.ReadAll(r.Body)
  1547. if err != nil {
  1548. t.Fatalf("handler ReadAll: %v", err)
  1549. }
  1550. if len(all) != 0 {
  1551. t.Errorf("handler got %d bytes; expected 0", len(all))
  1552. }
  1553. rw.Header().Set("Content-Length", "0")
  1554. }))
  1555. defer ts.Close()
  1556. req, err := NewRequest("POST", ts.URL, strings.NewReader(""))
  1557. if err != nil {
  1558. t.Fatal(err)
  1559. }
  1560. req.ContentLength = 0
  1561. var resp [5]*Response
  1562. for i := range resp {
  1563. resp[i], err = DefaultClient.Do(req)
  1564. if err != nil {
  1565. t.Fatalf("client post #%d: %v", i, err)
  1566. }
  1567. }
  1568. for i := range resp {
  1569. all, err := ioutil.ReadAll(resp[i].Body)
  1570. if err != nil {
  1571. t.Fatalf("req #%d: client ReadAll: %v", i, err)
  1572. }
  1573. if len(all) != 0 {
  1574. t.Errorf("req #%d: client got %d bytes; expected 0", i, len(all))
  1575. }
  1576. }
  1577. }
  1578. func TestHandlerPanicNil(t *testing.T) {
  1579. testHandlerPanic(t, false, nil)
  1580. }
  1581. func TestHandlerPanic(t *testing.T) {
  1582. testHandlerPanic(t, false, "intentional death for testing")
  1583. }
  1584. func TestHandlerPanicWithHijack(t *testing.T) {
  1585. testHandlerPanic(t, true, "intentional death for testing")
  1586. }
  1587. func testHandlerPanic(t *testing.T, withHijack bool, panicValue interface{}) {
  1588. defer afterTest(t)
  1589. // Unlike the other tests that set the log output to ioutil.Discard
  1590. // to quiet the output, this test uses a pipe. The pipe serves three
  1591. // purposes:
  1592. //
  1593. // 1) The log.Print from the http server (generated by the caught
  1594. // panic) will go to the pipe instead of stderr, making the
  1595. // output quiet.
  1596. //
  1597. // 2) We read from the pipe to verify that the handler
  1598. // actually caught the panic and logged something.
  1599. //
  1600. // 3) The blocking Read call prevents this TestHandlerPanic
  1601. // function from exiting before the HTTP server handler
  1602. // finishes crashing. If this text function exited too
  1603. // early (and its defer log.SetOutput(os.Stderr) ran),
  1604. // then the crash output could spill into the next test.
  1605. pr, pw := io.Pipe()
  1606. log.SetOutput(pw)
  1607. defer log.SetOutput(os.Stderr)
  1608. defer pw.Close()
  1609. ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  1610. if withHijack {
  1611. rwc, _, err := w.(Hijacker).Hijack()
  1612. if err != nil {
  1613. t.Logf("unexpected error: %v", err)
  1614. }
  1615. defer rwc.Close()
  1616. }
  1617. panic(panicValue)
  1618. }))
  1619. defer ts.Close()
  1620. // Do a blocking read on the log output pipe so its logging
  1621. // doesn't bleed into the next test. But wait only 5 seconds
  1622. // for it.
  1623. done := make(chan bool, 1)
  1624. go func() {
  1625. buf := make([]byte, 4<<10)
  1626. _, err := pr.Read(buf)
  1627. pr.Close()
  1628. if err != nil && err != io.EOF {
  1629. t.Error(err)
  1630. }
  1631. done <- true
  1632. }()
  1633. _, err := Get(ts.URL)
  1634. if err == nil {
  1635. t.Logf("expected an error")
  1636. }
  1637. if panicValue == nil {
  1638. return
  1639. }
  1640. select {
  1641. case <-done:
  1642. return
  1643. case <-time.After(5 * time.Second):
  1644. t.Fatal("expected server handler to log an error")
  1645. }
  1646. }
  1647. func TestServerNoDate(t *testing.T) { testServerNoHeader(t, "Date") }
  1648. func TestServerNoContentType(t *testing.T) { testServerNoHeader(t, "Content-Type") }
  1649. func testServerNoHeader(t *testing.T, header string) {
  1650. defer afterTest(t)
  1651. ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  1652. w.Header()[header] = nil
  1653. io.WriteString(w, "<html>foo</html>") // non-empty
  1654. }))
  1655. defer ts.Close()
  1656. res, err := Get(ts.URL)
  1657. if err != nil {
  1658. t.Fatal(err)
  1659. }
  1660. res.Body.Close()
  1661. if got, ok := res.Header[header]; ok {
  1662. t.Fatalf("Expected no %s header; got %q", header, got)
  1663. }
  1664. }
  1665. func TestStripPrefix(t *testing.T) {
  1666. defer afterTest(t)
  1667. h := HandlerFunc(func(w ResponseWriter, r *Request) {
  1668. w.Header().Set("X-Path", r.URL.Path)
  1669. })
  1670. ts := httptest.NewServer(StripPrefix("/foo", h))
  1671. defer ts.Close()
  1672. res, err := Get(ts.URL + "/foo/bar")
  1673. if err != nil {
  1674. t.Fatal(err)
  1675. }
  1676. if g, e := res.Header.Get("X-Path"), "/bar"; g != e {
  1677. t.Errorf("test 1: got %s, want %s", g, e)
  1678. }
  1679. res.Body.Close()
  1680. res, err = Get(ts.URL + "/bar")
  1681. if err != nil {
  1682. t.Fatal(err)
  1683. }
  1684. if g, e := res.StatusCode, 404; g != e {
  1685. t.Errorf("test 2: got status %v, want %v", g, e)
  1686. }
  1687. res.Body.Close()
  1688. }
  1689. func TestRequestLimit(t *testing.T) {
  1690. defer afterTest(t)
  1691. ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  1692. t.Fatalf("didn't expect to get request in Handler")
  1693. }))
  1694. defer ts.Close()
  1695. req, _ := NewRequest("GET", ts.URL, nil)
  1696. var b

Large files files are truncated, but you can click here to view the full file