-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathperformance_test.go
88 lines (74 loc) · 2.27 KB
/
performance_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package middleware_test
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/cixtor/middleware"
)
type CustomResponseWriter struct {
body []byte
code int
head http.Header
}
func NewCustomResponseWriter() *CustomResponseWriter {
return &CustomResponseWriter{
head: http.Header{},
}
}
func (crw *CustomResponseWriter) Header() http.Header {
return crw.head
}
func (crw *CustomResponseWriter) Write(b []byte) (int, error) {
crw.body = b
return len(b), nil
}
func (crw *CustomResponseWriter) WriteHeader(statusCode int) {
crw.code = statusCode
}
// BenchmarkServeHTTP checks the performance of the ServeHTTP method.
//
// go test -bench .
//
// Results:
//
// - Average is 432058 and 6024 ns/op (rudimentary router)
// - Average is 293815 and 3909 ns/op (sophisticated router)
// - Average is 678906 and 1415 ns/op (trie data structure)
func BenchmarkServeHTTP(b *testing.B) {
w := NewCustomResponseWriter()
r := httptest.NewRequest(http.MethodGet, "/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o"+
"/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/a/b/c/d/e/f/g/h"+
"/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p"+
"/q/r/s/t/u/v/w/x/y/z/p/q/r/s/t/u/v/w/x/y/z/a/b/c/d/e/f/g/h/i/j/k/l/m"+
"/n/o/p/q/r/s/t/u/v/w/x/y/z/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u"+
"/v/w/x/y/z", nil)
srv := middleware.New()
srv.GET("/a/b/c/*", func(w http.ResponseWriter, r *http.Request) { /* ... */ })
srv.DiscardLogs()
for n := 0; n < b.N; n++ {
srv.ServeHTTP(w, r)
}
}
// FuzzServeHTTP checks for panics somewhere in the ServeHTTP operations.
//
// go test -fuzz FuzzServeHTTP -fuzztime 30s
func FuzzServeHTTP(f *testing.F) {
f.Add("GET", "/")
f.Add("POST", "/hello/world")
f.Add("HEAD", "/////hello/world")
f.Add("PUT", "/server-status")
f.Add("DELETE", "/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z")
w := NewCustomResponseWriter()
r := httptest.NewRequest(http.MethodGet, "/", nil)
h := func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("fuzz")) }
x := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("404 fuzz page"))
})
f.Fuzz(func(t *testing.T, method string, endpoint string) {
srv := middleware.New()
srv.DiscardLogs()
srv.NotFound = x
srv.Handle(method, endpoint, h)
srv.ServeHTTP(w, r)
})
}