...

Source file src/github.com/felixge/httpsnoop/bench_test.go

Documentation: github.com/felixge/httpsnoop

     1  package httpsnoop
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"testing"
     7  )
     8  
     9  func BenchmarkBaseline(b *testing.B) {
    10  	benchmark(b, 0)
    11  }
    12  
    13  func BenchmarkCaptureMetrics(b *testing.B) {
    14  	benchmark(b, 1)
    15  }
    16  
    17  func BenchmarkCaptureMetricsTwice(b *testing.B) {
    18  	benchmark(b, 2)
    19  }
    20  
    21  func BenchmarkWrap(b *testing.B) {
    22  	b.StopTimer()
    23  	doneCh := make(chan struct{}, 1)
    24  	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    25  		b.StartTimer()
    26  		for i := 0; i < b.N; i++ {
    27  			Wrap(w, Hooks{})
    28  		}
    29  		doneCh <- struct{}{}
    30  	})
    31  	s := httptest.NewServer(h)
    32  	defer s.Close()
    33  	if _, err := http.Get(s.URL); err != nil {
    34  		b.Fatal(err)
    35  	}
    36  	<-doneCh
    37  }
    38  
    39  func benchmark(b *testing.B, wrappings int) {
    40  	dummyH := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
    41  	h := dummyH
    42  	for x := 0; x < wrappings; x++ {
    43  		hCopy := h
    44  		h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    45  			CaptureMetrics(hCopy, w, r)
    46  		})
    47  	}
    48  
    49  	req := httptest.NewRequest(http.MethodGet, "/", http.NoBody)
    50  	resp := httptest.NewRecorder() // ok to reuse; we're not writing anything to it
    51  
    52  	b.ReportAllocs()
    53  	b.ResetTimer()
    54  
    55  	for i := 0; i < b.N; i++ {
    56  		h.ServeHTTP(resp, req)
    57  	}
    58  }
    59  

View as plain text