go.sdls.io/sin@v0.0.9/pkg/sin/benchmarks_test.go (about) 1 // Copyright 2017 Manu Martinez-Almeida. All rights reserved. 2 // Use of this source code is governed by a MIT style 3 // license that can be found in the LICENSE file. 4 5 package sin 6 7 import ( 8 "net/http" 9 "testing" 10 ) 11 12 func BenchmarkOneRoute(B *testing.B) { 13 router := New() 14 router.GET("/ping", func(c *Context) {}) 15 runRequest(B, router, "GET", "/ping") 16 } 17 18 func BenchmarkOneRouteJSON(B *testing.B) { 19 router := New() 20 data := struct { 21 Status string `json:"status"` 22 }{"ok"} 23 router.GET("/json", func(c *Context) { 24 c.JSON(http.StatusOK, data) 25 }) 26 runRequest(B, router, "GET", "/json") 27 } 28 29 func BenchmarkOneRouteSet(B *testing.B) { 30 router := New() 31 router.GET("/ping", func(c *Context) { 32 c.Set("key", "value") 33 }) 34 runRequest(B, router, "GET", "/ping") 35 } 36 37 func BenchmarkOneRouteString(B *testing.B) { 38 router := New() 39 router.GET("/text", func(c *Context) { 40 c.String(http.StatusOK, "this is a plain text") 41 }) 42 runRequest(B, router, "GET", "/text") 43 } 44 45 func BenchmarkManyRoutesFist(B *testing.B) { 46 router := New() 47 router.Any("/ping", func(c *Context) {}) 48 runRequest(B, router, "GET", "/ping") 49 } 50 51 func BenchmarkManyRoutesLast(B *testing.B) { 52 router := New() 53 router.Any("/ping", func(c *Context) {}) 54 runRequest(B, router, "OPTIONS", "/ping") 55 } 56 57 func Benchmark404(B *testing.B) { 58 router := New() 59 router.Any("/something", func(c *Context) {}) 60 router.NoRoute(func(c *Context) {}) 61 runRequest(B, router, "GET", "/ping") 62 } 63 64 func Benchmark404Many(B *testing.B) { 65 router := New() 66 router.GET("/", func(c *Context) {}) 67 router.GET("/path/to/something", func(c *Context) {}) 68 router.GET("/post/:id", func(c *Context) {}) 69 router.GET("/view/:id", func(c *Context) {}) 70 router.GET("/favicon.ico", func(c *Context) {}) 71 router.GET("/robots.txt", func(c *Context) {}) 72 router.GET("/delete/:id", func(c *Context) {}) 73 router.GET("/user/:id/:mode", func(c *Context) {}) 74 75 router.NoRoute(func(c *Context) {}) 76 runRequest(B, router, "GET", "/viewfake") 77 } 78 79 type mockWriter struct { 80 headers http.Header 81 } 82 83 func newMockWriter() *mockWriter { 84 return &mockWriter{ 85 http.Header{}, 86 } 87 } 88 89 func (m *mockWriter) Header() (h http.Header) { 90 return m.headers 91 } 92 93 func (m *mockWriter) Write(p []byte) (n int, err error) { 94 return len(p), nil 95 } 96 97 func (m *mockWriter) WriteString(s string) (n int, err error) { 98 return len(s), nil 99 } 100 101 func (m *mockWriter) WriteHeader(int) {} 102 103 func runRequest(B *testing.B, r *Engine, method, path string) { 104 // create fake request 105 req, err := http.NewRequest(method, path, nil) 106 if err != nil { 107 panic(err) 108 } 109 w := newMockWriter() 110 B.ReportAllocs() 111 B.ResetTimer() 112 for i := 0; i < B.N; i++ { 113 r.ServeHTTP(w, req) 114 } 115 }