perf(path): replace regex with custom functions in redirectTrailingSlash (#4414)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* perf: replace regex with custom functions in redirectTrailingSlash * perf: use more efficient removeRepeatedChar for path slash handling ---------
authored by Name · committed by GitHub · parent ecb3f7b · Browse files · 3 files·+114 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: 1911860538 <alxps1911@gmail.com>
Diff stats
3 files+114 added−9 removed
- other:+114 added−9 removed
Provenance
- Commit
440eb14- Tree
fa13300- Author
Name <1911860538@qq.com>- Committer
GitHub <noreply@github.com>- Parent
ecb3f7b
3 files changed+114 added−9 removed
modified:gin.go+13 added-8 removed
9 unmodified lines10 "net"11 "net/http"12 "os"13 "path"14- "regexp"14 "strings"15 "sync"16 17 "github.com/gin-gonic/gin/internal/bytesconv"28 unmodified lines46 Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},47 },48 }49 51-var (52- regSafePrefix = regexp.MustCompile("[^a-zA-Z0-9/-]+")53- regRemoveRepeatedChar = regexp.MustCompile("/{2,}")54-)55-50 // HandlerFunc defines the handler used by gin middleware as return value.51 type HandlerFunc func(*Context)52 53 // OptionFunc defines the function to change the default configuration715 unmodified lines769 func redirectTrailingSlash(c *Context) {770 req := c.Request771 p := req.URL.Path772 if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." {779- prefix = regSafePrefix.ReplaceAllString(prefix, "")780- prefix = regRemoveRepeatedChar.ReplaceAllString(prefix, "/")773+ prefix = sanitizePathChars(prefix)774+ prefix = removeRepeatedChar(prefix, '/')775 776 p = prefix + "/" + req.URL.Path777 }778 req.URL.Path = p + "/"2 unmodified lines781 }782 redirectRequest(c)783 }784 785+// sanitizePathChars removes unsafe characters from path strings,786+// keeping only ASCII letters, ASCII numbers, forward slashes, and hyphens.787+func sanitizePathChars(s string) string {788+ return strings.Map(func(r rune) rune {789+ if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '/' || r == '-' {790+ return r791+ }792+ return -1793+ }, s)794+}795+796 func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool {797 req := c.Request798 rPath := req.URL.Path799 21 unmodified linesmodified:path_test.go+47 added
141 unmodified lines142 cleanPath(test.path)143 }144 }145 }146+147+func TestRemoveRepeatedChar(t *testing.T) {148+ testCases := []struct {149+ name string150+ str string151+ char byte152+ want string153+ }{154+ {155+ name: "empty",156+ str: "",157+ char: 'a',158+ want: "",159+ },160+ {161+ name: "noSlash",162+ str: "abc",163+ char: ',',164+ want: "abc",165+ },166+ {167+ name: "withSlash",168+ str: "/a/b/c/",169+ char: '/',170+ want: "/a/b/c/",171+ },172+ {173+ name: "withRepeatedSlashes",174+ str: "/a//b///c////",175+ char: '/',176+ want: "/a/b/c/",177+ },178+ {179+ name: "threeSlashes",180+ str: "///",181+ char: '/',182+ want: "/",183+ },184+ }185+186+ for _, tc := range testCases {187+ t.Run(tc.name, func(t *testing.T) {188+ res := removeRepeatedChar(tc.str, tc.char)189+ assert.Equal(t, tc.want, res)190+ })191+ }192+}modified:path.go+54 added-1 removed
3 unmodified lines4 // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE.5 6 package gin7 8+const stackBufSize = 1289+10 // cleanPath is the URL version of path.Clean, it returns a canonical URL path11 // for p, eliminating . and .. elements.12 //13 // The following rules are applied iteratively until no further processing can6 unmodified lines20 // that is, replace "/.." by "/" at the beginning of a path.21 //22 // If the result of this process is an empty string, "/" is returned.23 func cleanPath(p string) string {22- const stackBufSize = 12824 // Turn empty string into "/"25 if p == "" {26 return "/"27 }120 unmodified lines148 copy(b, s[:w])149 }150 b[w] = c151 }152+153+// removeRepeatedChar removes multiple consecutive 'char's from a string.154+// if s == "/a//b///c////" && char == '/', it returns "/a/b/c/"155+func removeRepeatedChar(s string, char byte) string {156+ // Check if there are any consecutive chars157+ hasRepeatedChar := false158+ for i := 1; i < len(s); i++ {159+ if s[i] == char && s[i-1] == char {160+ hasRepeatedChar = true161+ break162+ }163+ }164+ if !hasRepeatedChar {165+ return s166+ }167+168+ // Reasonably sized buffer on stack to avoid allocations in the common case.169+ buf := make([]byte, 0, stackBufSize)170+171+ // Invariants:172+ // reading from s; r is index of next byte to process.173+ // writing to buf; w is index of next byte to write.174+ r := 0175+ w := 0176+177+ for n := len(s); r < n; {178+ if s[r] == char {179+ // Write the first char180+ bufApp(&buf, s, w, char)181+ w++182+ r++183+184+ // Skip all consecutive chars185+ for r < n && s[r] == char {186+ r++187+ }188+ } else {189+ // Copy non-char character190+ bufApp(&buf, s, w, s[r])191+ w++192+ r++193+ }194+ }195+196+ // If the original string was not modified (or only shortened at the end),197+ // return the respective substring of the original string.198+ // Otherwise, return a new string from the buffer.199+ if len(buf) == 0 {200+ return s[:w]201+ }202+ return string(buf[:w])203+}