forge.chapril.org/losyme/kong@v0.0.0-20220510163801-37a2e4eef4e2/router/benchmark_test.go (about) 1 /* 2 ------------------------------------------------------------------------------------------------------------------------ 3 ####### kong ####### Copyright (c) 2021-2022 losyme ################################################ MIT License ####### 4 ------------------------------------------------------------------------------------------------------------------------ 5 */ 6 7 package router 8 9 import ( 10 "net/http" 11 "testing" 12 13 "forge.chapril.org/losyme/kong/context" 14 ) 15 16 func BenchmarkOneRoute(B *testing.B) { 17 router := New(context.RendererTypeJSON) 18 router.Get("/ping", func(c *context.Context) error { 19 return nil 20 }) 21 runRequest(B, router, "GET", "/ping") 22 } 23 24 type mockWriter struct { 25 headers http.Header 26 } 27 28 func newMockWriter() *mockWriter { 29 return &mockWriter{ 30 http.Header{}, 31 } 32 } 33 34 func (m *mockWriter) Header() (h http.Header) { 35 return m.headers 36 } 37 38 func (m *mockWriter) Write(p []byte) (n int, err error) { 39 return len(p), nil 40 } 41 42 func (m *mockWriter) WriteString(s string) (n int, err error) { 43 return len(s), nil 44 } 45 46 func (m *mockWriter) WriteHeader(int) {} 47 48 func runRequest(B *testing.B, r *Router, method, path string) { 49 req, err := http.NewRequest(method, path, nil) 50 if err != nil { 51 panic(err) 52 } 53 54 rw := newMockWriter() 55 56 B.ReportAllocs() 57 B.ResetTimer() 58 59 sr := r.SubRouter 60 61 for i := 0; i < B.N; i++ { 62 sr.ServeHTTP(rw, req) 63 } 64 } 65 66 /* 67 ######################################################################################################## @(°_°)@ ####### 68 */