github.com/ccccaoqing/test@v0.0.0-20220510085219-3985d23445c0/test/bench/go1/http_test.go (about) 1 // Copyright 2013 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 go1 6 7 import ( 8 "bytes" 9 "io/ioutil" 10 "net/http" 11 "net/http/httptest" 12 "testing" 13 ) 14 15 // BenchmarkHTTPClientServer benchmarks both the HTTP client and the HTTP server, 16 // on small requests. 17 func BenchmarkHTTPClientServer(b *testing.B) { 18 msg := []byte("Hello world.\n") 19 ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { 20 rw.Write(msg) 21 })) 22 defer ts.Close() 23 24 tr := &http.Transport{} 25 defer tr.CloseIdleConnections() 26 cl := &http.Client{ 27 Transport: tr, 28 } 29 30 b.ResetTimer() 31 32 for i := 0; i < b.N; i++ { 33 res, err := cl.Get(ts.URL) 34 if err != nil { 35 b.Fatal("Get:", err) 36 } 37 all, err := ioutil.ReadAll(res.Body) 38 if err != nil { 39 b.Fatal("ReadAll:", err) 40 } 41 if !bytes.Equal(all, msg) { 42 b.Fatalf("Got body %q; want %q", all, msg) 43 } 44 } 45 }