Permalink
Browse files

Pre-compiling regexp to make JSONP a bit faster

  • Loading branch information...
paulbellamy committed Jun 12, 2011
1 parent ebf2610 commit c53edfe2eed71ba6de76f0e85082ee7123d59a37
Showing with 51 additions and 1 deletion.
  1. +3 −1 jsonp.go
  2. +48 −0 jsonp_test.go
View
@@ -6,11 +6,13 @@ import (
"strings"
)
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$]*)*$")
func JSONP(env Env, app App) (Status, Headers, Body) {
callback := env.Request().FormValue("callback")
if callback != "" {
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 {
if !jsonp_valid_callback_matcher.MatchString(callback) {
return 400, Headers{"Content-Type": []string{"text/plain"}, "Content-Length": []string{"11"}}, "Bad Request"
}
}
View
@@ -161,3 +161,51 @@ func BenchmarkJSONP(b *testing.B) {
}
b.StopTimer()
}
func BenchmarkNonJSONP(b *testing.B) {
b.StopTimer()
nonJsonpStack := new(Stack)
nonJsonpStack.Middleware(JSONP)
nonJsonpApp := nonJsonpStack.Compile(nonJsonServer)
request, _ := http.NewRequest("GET", "http://localhost:3000/?callback=parseResponse", nil)
b.StartTimer()
for i := 0; i < b.N; i++ {
nonJsonpApp(Env{"mango.request": &Request{request}})
}
b.StopTimer()
}
func BenchmarkJSONPNoCallback(b *testing.B) {
b.StopTimer()
jsonpStack := new(Stack)
jsonpStack.Middleware(JSONP)
jsonpApp := jsonpStack.Compile(jsonServer)
request, _ := http.NewRequest("GET", "http://localhost:3000/", nil)
b.StartTimer()
for i := 0; i < b.N; i++ {
jsonpApp(Env{"mango.request": &Request{request}})
}
b.StopTimer()
}
func BenchmarkJSONPInvalidCallback(b *testing.B) {
b.StopTimer()
jsonpStack := new(Stack)
jsonpStack.Middleware(JSONP)
jsonpApp := jsonpStack.Compile(jsonServer)
request, _ := http.NewRequest("GET", "http://localhost:3000/?callback=invalid(callback)", nil)
b.StartTimer()
for i := 0; i < b.N; i++ {
jsonpApp(Env{"mango.request": &Request{request}})
}
b.StopTimer()
}

0 comments on commit c53edfe

Please sign in to comment.