git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/httpx/cors/bench_test.go (about) 1 package cors 2 3 import ( 4 "net/http" 5 "testing" 6 ) 7 8 type FakeResponse struct { 9 header http.Header 10 } 11 12 func (r FakeResponse) Header() http.Header { 13 return r.header 14 } 15 16 func (r FakeResponse) WriteHeader(n int) { 17 } 18 19 func (r FakeResponse) Write(b []byte) (n int, err error) { 20 return len(b), nil 21 } 22 23 func BenchmarkWithout(b *testing.B) { 24 res := FakeResponse{http.Header{}} 25 req, _ := http.NewRequest("GET", "http://example.com/foo", nil) 26 27 b.ReportAllocs() 28 b.ResetTimer() 29 for i := 0; i < b.N; i++ { 30 testHandler.ServeHTTP(res, req) 31 } 32 } 33 34 func BenchmarkDefault(b *testing.B) { 35 res := FakeResponse{http.Header{}} 36 req, _ := http.NewRequest("GET", "http://example.com/foo", nil) 37 req.Header.Add("Origin", "somedomain.com") 38 handler := Default().Handler(testHandler) 39 40 b.ReportAllocs() 41 b.ResetTimer() 42 for i := 0; i < b.N; i++ { 43 handler.ServeHTTP(res, req) 44 } 45 } 46 47 func BenchmarkAllowedOrigin(b *testing.B) { 48 res := FakeResponse{http.Header{}} 49 req, _ := http.NewRequest("GET", "http://example.com/foo", nil) 50 req.Header.Add("Origin", "somedomain.com") 51 c := New(Options{ 52 AllowedOrigins: []string{"somedomain.com"}, 53 }) 54 handler := c.Handler(testHandler) 55 56 b.ReportAllocs() 57 b.ResetTimer() 58 for i := 0; i < b.N; i++ { 59 handler.ServeHTTP(res, req) 60 } 61 } 62 63 func BenchmarkPreflight(b *testing.B) { 64 res := FakeResponse{http.Header{}} 65 req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil) 66 req.Header.Add("Access-Control-Request-Method", "GET") 67 handler := Default().Handler(testHandler) 68 69 b.ReportAllocs() 70 b.ResetTimer() 71 for i := 0; i < b.N; i++ { 72 handler.ServeHTTP(res, req) 73 } 74 } 75 76 func BenchmarkPreflightHeader(b *testing.B) { 77 res := FakeResponse{http.Header{}} 78 req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil) 79 req.Header.Add("Access-Control-Request-Method", "GET") 80 req.Header.Add("Access-Control-Request-Headers", "Accept") 81 handler := Default().Handler(testHandler) 82 83 b.ReportAllocs() 84 b.ResetTimer() 85 for i := 0; i < b.N; i++ { 86 handler.ServeHTTP(res, req) 87 } 88 }