-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbench_test.go
71 lines (55 loc) · 1.46 KB
/
bench_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
package fastroute
import (
"net/http"
"testing"
)
func Benchmark_1Param(b *testing.B) {
router := Route("/v1/users/:id", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(Parameters(r).ByName("id")))
})
req, err := http.NewRequest("GET", "http://localhost:8080/v1/users/5", nil)
if err != nil {
b.Fatal(err)
}
benchRequest(b, router, req)
}
func Benchmark_5Routes(b *testing.B) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(Parameters(r).ByName("id")))
}
router := New(
Route("/test/:id", handler),
Route("/puff/path/:id", handler),
Route("/home/user/:id", handler),
Route("/home/jey/:id/:cat", handler),
Route("/base/:id/user", handler),
)
req, err := http.NewRequest("GET", "http://localhost:8080/home/jey/5/user", nil)
if err != nil {
b.Fatal(err)
}
benchRequest(b, router, req)
}
type mockResponseWriter struct{}
func (m *mockResponseWriter) Header() (h http.Header) {
return http.Header{}
}
func (m *mockResponseWriter) Write(p []byte) (n int, err error) {
return len(p), nil
}
func (m *mockResponseWriter) WriteString(s string) (n int, err error) {
return len(s), nil
}
func (m *mockResponseWriter) WriteHeader(int) {}
func benchRequest(b *testing.B, router http.Handler, r *http.Request) {
w := new(mockResponseWriter)
u := r.URL
rq := u.RawQuery
r.RequestURI = u.RequestURI()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
u.RawQuery = rq
router.ServeHTTP(w, r)
}
}