Skip to content

Commit c53edfe

Browse files
committed
Pre-compiling regexp to make JSONP a bit faster
1 parent ebf2610 commit c53edfe

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

jsonp.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,13 @@ import (
66
"strings"
77
)
88

9+
var jsonp_valid_callback_matcher *regexp.Regexp = regexp.MustCompile("^[a-zA-Z_$][a-zA-Z_0-9$]*([.]?[a-zA-Z_$][a-zA-Z_0-9$]*)*$")
10+
911
func JSONP(env Env, app App) (Status, Headers, Body) {
1012
callback := env.Request().FormValue("callback")
1113

1214
if callback != "" {
13-
if matched, err := regexp.MatchString("^[a-zA-Z_$][a-zA-Z_0-9$]*([.]?[a-zA-Z_$][a-zA-Z_0-9$]*)*$", callback); !matched || err != nil {
15+
if !jsonp_valid_callback_matcher.MatchString(callback) {
1416
return 400, Headers{"Content-Type": []string{"text/plain"}, "Content-Length": []string{"11"}}, "Bad Request"
1517
}
1618
}

jsonp_test.go

+48
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,51 @@ func BenchmarkJSONP(b *testing.B) {
161161
}
162162
b.StopTimer()
163163
}
164+
165+
func BenchmarkNonJSONP(b *testing.B) {
166+
b.StopTimer()
167+
168+
nonJsonpStack := new(Stack)
169+
nonJsonpStack.Middleware(JSONP)
170+
nonJsonpApp := nonJsonpStack.Compile(nonJsonServer)
171+
172+
request, _ := http.NewRequest("GET", "http://localhost:3000/?callback=parseResponse", nil)
173+
174+
b.StartTimer()
175+
for i := 0; i < b.N; i++ {
176+
nonJsonpApp(Env{"mango.request": &Request{request}})
177+
}
178+
b.StopTimer()
179+
}
180+
181+
func BenchmarkJSONPNoCallback(b *testing.B) {
182+
b.StopTimer()
183+
184+
jsonpStack := new(Stack)
185+
jsonpStack.Middleware(JSONP)
186+
jsonpApp := jsonpStack.Compile(jsonServer)
187+
188+
request, _ := http.NewRequest("GET", "http://localhost:3000/", nil)
189+
190+
b.StartTimer()
191+
for i := 0; i < b.N; i++ {
192+
jsonpApp(Env{"mango.request": &Request{request}})
193+
}
194+
b.StopTimer()
195+
}
196+
197+
func BenchmarkJSONPInvalidCallback(b *testing.B) {
198+
b.StopTimer()
199+
200+
jsonpStack := new(Stack)
201+
jsonpStack.Middleware(JSONP)
202+
jsonpApp := jsonpStack.Compile(jsonServer)
203+
204+
request, _ := http.NewRequest("GET", "http://localhost:3000/?callback=invalid(callback)", nil)
205+
206+
b.StartTimer()
207+
for i := 0; i < b.N; i++ {
208+
jsonpApp(Env{"mango.request": &Request{request}})
209+
}
210+
b.StopTimer()
211+
}

0 commit comments

Comments
 (0)