-
Notifications
You must be signed in to change notification settings - Fork 0
/
router_bench_test.go
63 lines (55 loc) · 1.53 KB
/
router_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
package router
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
// BenchmarkRouter measures the performance of the router under load.
func BenchmarkRouter(b *testing.B) {
// Set up the router
mux := http.NewServeMux()
router := New(mux, "Example API", "1.0.0")
// Register a large number of routes to simulate complexity
numRoutes := 1000
// Register routes at the root level
for i := 0; i < numRoutes; i++ {
path := fmt.Sprintf("/users/%d", i)
router.Get(path, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "User")
})
}
// Register routes within a group
router.Group("/api", func(api *Router) {
for i := 0; i < numRoutes; i++ {
path := fmt.Sprintf("/items/%d", i)
api.Get(path, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Item")
})
}
})
// Create test requests for benchmarking
requests := make([]*http.Request, 0, numRoutes*2)
for i := 0; i < numRoutes; i++ {
path := fmt.Sprintf("/users/%d", i)
req := httptest.NewRequest("GET", path, nil)
requests = append(requests, req)
}
for i := 0; i < numRoutes; i++ {
path := fmt.Sprintf("/api/items/%d", i)
req := httptest.NewRequest("GET", path, nil)
requests = append(requests, req)
}
// Reset the timer to exclude setup time
b.ResetTimer()
// Run the benchmark
for i := 0; i < b.N; i++ {
for _, req := range requests {
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Result().StatusCode != http.StatusOK {
b.Errorf("Expected status 200, got %d", w.Result().StatusCode)
}
}
}
}