github.com/sleep2death/gotham@v1.0.2/benchmarks_test.go (about) 1 package gotham 2 3 import ( 4 "testing" 5 6 "github.com/golang/protobuf/proto" 7 "github.com/sleep2death/gotham/pb" 8 ) 9 10 func BenchmarkOneRoute(B *testing.B) { 11 router := New() 12 router.Handle("pb.Ping", func(c *Context) { 13 }) 14 runRequest(B, router, "pb.Ping") 15 } 16 17 func BenchmarkWithRecoveryMiddleware(B *testing.B) { 18 router := New() 19 router.Use(Recovery()) 20 router.Handle("pb.Ping", func(c *Context) { 21 }) 22 runRequest(B, router, "pb.Ping") 23 } 24 25 func BenchmarkLoggerMiddleware(B *testing.B) { 26 router := New() 27 router.Use(LoggerWithWriter(new(mockIOWriter))) 28 29 router.Handle("/pb/Ping", func(c *Context) { 30 }) 31 runRequest(B, router, "/pb/Ping") 32 } 33 34 func BenchmarkManyHandlers(B *testing.B) { 35 router := New() 36 router.Use(Recovery(), LoggerWithWriter(new(mockIOWriter))) 37 router.Use(func(c *Context) {}) 38 router.Use(func(c *Context) {}) 39 router.Handle("pb.Ping", func(c *Context) {}) 40 runRequest(B, router, "pb.Ping") 41 } 42 43 func BenchmarkDecodeAndEncode(B *testing.B) { 44 router := New() 45 router.Handle("pb.Ping", func(c *Context) { 46 msg := new(pb.Ping) 47 proto.Unmarshal(c.Request.Data.([]byte), msg) 48 49 msg.Message = "Pong" 50 c.Write(msg) 51 }) 52 53 runRequest(B, router, "pb.Ping") 54 } 55 56 func BenchmarkOneRouteSet(B *testing.B) { 57 router := New() 58 router.Handle("pb.Ping", func(c *Context) { 59 c.Set("hello", "world") 60 }) 61 runRequest(B, router, "pb.Ping") 62 } 63 64 type mockWriter struct{} 65 66 func (mw *mockWriter) Flush() error { return nil } 67 func (mw *mockWriter) Buffered() int { return 0 } 68 func (mw *mockWriter) SetStatus(code int) {} 69 func (mw *mockWriter) Status() int { return 200 } 70 func (mw *mockWriter) KeepAlive() bool { return true } 71 func (mw *mockWriter) SetKeepAlive(value bool) {} 72 func (mw *mockWriter) Write(data interface{}) error { return nil } 73 74 type mockIOWriter struct{} 75 76 func (rw *mockIOWriter) Write(b []byte) (int, error) { 77 return len(b), nil 78 } 79 80 func runRequest(B *testing.B, r *Router, path string) { 81 SetMode("release") 82 // fake request 83 msg := pb.Ping{Message: "Ping"} 84 data, _ := proto.Marshal(&msg) 85 req := &Request{TypeURL: path, Data: data} 86 87 w := &mockWriter{} 88 89 B.ReportAllocs() 90 B.ResetTimer() 91 92 for i := 0; i < B.N; i++ { 93 r.ServeProto(w, req) 94 } 95 }