Skip to content

Commit b76b288

Browse files
author
Kush Mansingh
committed
Remove unneccessary regex matching, substitute with string slicing
1 parent 8f41eac commit b76b288

File tree

2 files changed

+10
-11
lines changed

2 files changed

+10
-11
lines changed

mux.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"net/http"
1111
"path"
1212
"regexp"
13+
"strings"
1314
)
1415

1516
// NewRouter returns a new router instance.
@@ -367,10 +368,11 @@ func getPath(req *http.Request) string {
367368
// as detailed here as detailed in https://golang.org/pkg/net/url/#URL
368369
// for < 1.5 server side workaround
369370
// http://localhost/path/here?v=1 -> /path/here
370-
re := regexp.MustCompile(req.URL.Scheme + `://` + req.URL.Host)
371-
path := re.ReplaceAllLiteralString(req.RequestURI, "")
372-
re = regexp.MustCompile(`\?` + req.URL.RawQuery)
373-
path = re.ReplaceAllLiteralString(path, "")
371+
iStart := len(req.URL.Scheme + `://` + req.URL.Host)
372+
path := req.RequestURI[iStart:]
373+
if i := strings.LastIndex(path, "?"); i > -1 {
374+
path = path[:i]
375+
}
374376
return path
375377
}
376378
return req.URL.Path

mux_test.go

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"errors"
1111
"fmt"
1212
"net/http"
13-
"regexp"
1413
"strings"
1514
"testing"
1615
)
@@ -1490,12 +1489,10 @@ func newRequest(method, url string) *http.Request {
14901489
}
14911490
// extract the escaped original host+path from url
14921491
// http://localhost/path/here?v=1#frag -> //localhost/path/here
1493-
re := regexp.MustCompile(req.URL.Scheme + ":")
1494-
opaque := re.ReplaceAllLiteralString(url, "")
1495-
re = regexp.MustCompile(`\?` + req.URL.RawQuery)
1496-
opaque = re.ReplaceAllLiteralString(opaque, "")
1497-
re = regexp.MustCompile(`#` + req.URL.Fragment)
1498-
opaque = re.ReplaceAllLiteralString(opaque, "")
1492+
opaque := url[len(req.URL.Scheme)+1:]
1493+
if i := strings.LastIndex(opaque, "?"); i > -1 {
1494+
opaque = opaque[:i]
1495+
}
14991496

15001497
// Escaped host+path workaround as detailed in https://golang.org/pkg/net/url/#URL
15011498
// for < 1.5 client side workaround

0 commit comments

Comments
 (0)