Skip to content

Commit

Permalink
Use utils Trim functions instead of the strings/bytes functions (#3087)
Browse files Browse the repository at this point in the history
* Use utils Trim functions instead of the strings/bytes functions

* rename Test and Benchmark functions with same name
  • Loading branch information
ReneWerner87 committed Jul 24, 2024
1 parent e2cd100 commit fadedcb
Show file tree
Hide file tree
Showing 16 changed files with 46 additions and 43 deletions.
3 changes: 1 addition & 2 deletions client/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"io/fs"
"os"
"path/filepath"
"strings"
"sync"

"github.com/gofiber/utils/v2"
Expand Down Expand Up @@ -68,7 +67,7 @@ func (r *Response) Body() []byte {

// String method returns the body of the server response as String.
func (r *Response) String() string {
return strings.TrimSpace(string(r.Body()))
return utils.Trim(string(r.Body()), ' ')
}

// JSON method will unmarshal body to json.
Expand Down
10 changes: 5 additions & 5 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -778,7 +778,7 @@ iploop:
i++
}

s := strings.TrimRight(headerValue[i:j], " ")
s := utils.TrimRight(headerValue[i:j], ' ')

if c.app.config.EnableIPValidation {
// Skip validation if IP is clearly not IPv4/IPv6, otherwise validate without allocations
Expand Down Expand Up @@ -828,7 +828,7 @@ func (c *DefaultCtx) extractIPFromHeader(header string) string {
i++
}

s := strings.TrimRight(headerValue[i:j], " ")
s := utils.TrimRight(headerValue[i:j], ' ')

if c.app.config.EnableIPValidation {
if (!v6 && !v4) || (v6 && !utils.IsIPv6(s)) || (v4 && !utils.IsIPv4(s)) {
Expand Down Expand Up @@ -862,7 +862,7 @@ func (c *DefaultCtx) Is(extension string) bool {
}

return strings.HasPrefix(
strings.TrimLeft(utils.UnsafeString(c.fasthttp.Request.Header.ContentType()), " "),
utils.TrimLeft(utils.UnsafeString(c.fasthttp.Request.Header.ContentType()), ' '),
extensionHeader,
)
}
Expand Down Expand Up @@ -939,7 +939,7 @@ func (c *DefaultCtx) Links(link ...string) {
bb.WriteString(`; rel="` + link[i] + `",`)
}
}
c.setCanonical(HeaderLink, strings.TrimRight(c.app.getString(bb.Bytes()), ","))
c.setCanonical(HeaderLink, utils.TrimRight(c.app.getString(bb.Bytes()), ','))
bytebufferpool.Put(bb)
}

Expand Down Expand Up @@ -1810,7 +1810,7 @@ func (c *DefaultCtx) configDependentPaths() {
}
// If StrictRouting is disabled, we strip all trailing slashes
if !c.app.config.StrictRouting && len(c.detectionPathBuffer) > 1 && c.detectionPathBuffer[len(c.detectionPathBuffer)-1] == '/' {
c.detectionPathBuffer = bytes.TrimRight(c.detectionPathBuffer, "/")
c.detectionPathBuffer = utils.TrimRight(c.detectionPathBuffer, '/')
}
c.detectionPath = c.app.getString(c.detectionPathBuffer)

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/gofiber/fiber/v3
go 1.21

require (
github.com/gofiber/utils/v2 v2.0.0-beta.5
github.com/gofiber/utils/v2 v2.0.0-beta.6
github.com/google/uuid v1.6.0
github.com/mattn/go-colorable v0.1.13
github.com/mattn/go-isatty v0.0.20
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gofiber/utils/v2 v2.0.0-beta.5 h1:zbDIU8gVAlZ2Ak9Fk8APlis4S7wUiQFbcvv6UASkm6A=
github.com/gofiber/utils/v2 v2.0.0-beta.5/go.mod h1:3Kz8Px3jInKFvqxDzDeoSygwEOO+3uyubTmUa6PqY+0=
github.com/gofiber/utils/v2 v2.0.0-beta.6 h1:ED62bOmpRXdgviPlfTmf0Q+AXzhaTUAFtdWjgx+XkYI=
github.com/gofiber/utils/v2 v2.0.0-beta.6/go.mod h1:3Kz8Px3jInKFvqxDzDeoSygwEOO+3uyubTmUa6PqY+0=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
Expand Down
8 changes: 4 additions & 4 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ func getGroupPath(prefix, path string) string {
path = "/" + path
}

return strings.TrimRight(prefix, "/") + path
return utils.TrimRight(prefix, '/') + path
}

// acceptsOffer This function determines if an offer matches a given specification.
Expand Down Expand Up @@ -336,7 +336,7 @@ func getSplicedStrList(headerValue string, dst []string) []string {
dst = make([]string, len(dst)+(len(dst)>>1)+2)
copy(dst, oldSlice)
}
dst[insertIndex] = strings.TrimLeft(headerValue[lastElementEndsAt:index], " ")
dst[insertIndex] = utils.TrimLeft(headerValue[lastElementEndsAt:index], ' ')
lastElementEndsAt = uint8(index + 1)
insertIndex++
}
Expand All @@ -356,7 +356,7 @@ func forEachMediaRange(header []byte, functor func([]byte)) {

for len(header) > 0 {
n := 0
header = bytes.TrimLeft(header, " ")
header = utils.TrimLeft(header, ' ')
quotes := 0
escaping := false

Expand Down Expand Up @@ -459,7 +459,7 @@ func getOffer(header []byte, isAccepted func(spec, offer string, specParams head
}
}

spec = bytes.TrimSpace(spec)
spec = utils.Trim(spec, ' ')

// Determine specificity
var specificity int
Expand Down
8 changes: 4 additions & 4 deletions middleware/cache/manager_msgp_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions middleware/cors/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/log"
"github.com/gofiber/utils/v2"
)

// New creates a new middleware handler
Expand Down Expand Up @@ -44,15 +45,15 @@ func New(config ...Config) fiber.Handler {
break
}
if i := strings.Index(origin, "://*."); i != -1 {
trimmedOrigin := strings.TrimSpace(origin[:i+3] + origin[i+4:])
trimmedOrigin := utils.Trim(origin[:i+3]+origin[i+4:], ' ')
isValid, normalizedOrigin := normalizeOrigin(trimmedOrigin)
if !isValid {
panic("[CORS] Invalid origin format in configuration: " + trimmedOrigin)
}
sd := subdomain{prefix: normalizedOrigin[:i+3], suffix: normalizedOrigin[i+3:]}
allowSOrigins = append(allowSOrigins, sd)
} else {
trimmedOrigin := strings.TrimSpace(origin)
trimmedOrigin := utils.Trim(origin, ' ')
isValid, normalizedOrigin := normalizeOrigin(trimmedOrigin)
if !isValid {
panic("[CORS] Invalid origin format in configuration: " + trimmedOrigin)
Expand Down
5 changes: 3 additions & 2 deletions middleware/csrf/csrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"time"

"github.com/gofiber/fiber/v3"
"github.com/gofiber/utils/v2"
)

var (
Expand Down Expand Up @@ -62,15 +63,15 @@ func New(config ...Config) fiber.Handler {

for _, origin := range cfg.TrustedOrigins {
if i := strings.Index(origin, "://*."); i != -1 {
trimmedOrigin := strings.TrimSpace(origin[:i+3] + origin[i+4:])
trimmedOrigin := utils.Trim(origin[:i+3]+origin[i+4:], ' ')
isValid, normalizedOrigin := normalizeOrigin(trimmedOrigin)
if !isValid {
panic("[CSRF] Invalid origin format in configuration:" + origin)
}
sd := subdomain{prefix: normalizedOrigin[:i+3], suffix: normalizedOrigin[i+3:]}
trustedSubOrigins = append(trustedSubOrigins, sd)
} else {
trimmedOrigin := strings.TrimSpace(origin)
trimmedOrigin := utils.Trim(origin, ' ')
isValid, normalizedOrigin := normalizeOrigin(trimmedOrigin)
if !isValid {
panic("[CSRF] Invalid origin format in configuration:" + origin)
Expand Down
4 changes: 2 additions & 2 deletions middleware/csrf/csrf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ func Test_CSRF_WithSession(t *testing.T) {
h(ctx)
token := string(ctx.Response.Header.Peek(fiber.HeaderSetCookie))
for _, header := range strings.Split(token, ";") {
if strings.Split(strings.TrimSpace(header), "=")[0] == ConfigDefault.CookieName {
if strings.Split(utils.Trim(header, ' '), "=")[0] == ConfigDefault.CookieName {
token = strings.Split(header, "=")[1]
break
}
Expand Down Expand Up @@ -248,7 +248,7 @@ func Test_CSRF_ExpiredToken_WithSession(t *testing.T) {
h(ctx)
token := string(ctx.Response.Header.Peek(fiber.HeaderSetCookie))
for _, header := range strings.Split(token, ";") {
if strings.Split(strings.TrimSpace(header), "=")[0] == ConfigDefault.CookieName {
if strings.Split(utils.Trim(header, ' '), "=")[0] == ConfigDefault.CookieName {
token = strings.Split(header, "=")[1]
break
}
Expand Down
8 changes: 4 additions & 4 deletions middleware/csrf/manager_msgp_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions middleware/limiter/manager_msgp_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion middleware/pprof/pprof.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strings"

"github.com/gofiber/fiber/v3"
"github.com/gofiber/utils/v2"
"github.com/valyala/fasthttp/fasthttpadaptor"
)

Expand Down Expand Up @@ -71,7 +72,7 @@ func New(config ...Config) fiber.Handler {
default:
// pprof index only works with trailing slash
if strings.HasSuffix(path, "/") {
path = strings.TrimRight(path, "/")
path = utils.TrimRight(path, '/')
} else {
path = prefix + "/"
}
Expand Down
7 changes: 4 additions & 3 deletions mount.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ package fiber

import (
"sort"
"strings"
"sync"
"sync/atomic"

"github.com/gofiber/utils/v2"
)

// Put fields related to mounting.
Expand Down Expand Up @@ -39,7 +40,7 @@ func newMountFields(app *App) *mountFields {
// any of the fiber's sub apps are added to the application's error handlers
// to be invoked on errors that happen within the prefix route.
func (app *App) mount(prefix string, subApp *App) Router {
prefix = strings.TrimRight(prefix, "/")
prefix = utils.TrimRight(prefix, '/')
if prefix == "" {
prefix = "/"
}
Expand Down Expand Up @@ -69,7 +70,7 @@ func (app *App) mount(prefix string, subApp *App) Router {
// compose them as a single service using Mount.
func (grp *Group) mount(prefix string, subApp *App) Router {
groupPath := getGroupPath(grp.Prefix, prefix)
groupPath = strings.TrimRight(groupPath, "/")
groupPath = utils.TrimRight(groupPath, '/')
if groupPath == "" {
groupPath = "/"
}
Expand Down
6 changes: 3 additions & 3 deletions path.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const (
optionalParam byte = '?' // concludes a parameter by name and makes it optional
paramStarterChar byte = ':' // start character for a parameter with name
slashDelimiter byte = '/' // separator for the route, unlike the other delimiters this character at the end can be optional
slashDelimiterStr = "/" // separator for the route, unlike the other delimiters this character at the end can be optional
slashDelimiterStr byte = '/' // separator for the route, unlike the other delimiters this character at the end can be optional
escapeChar byte = '\\' // escape character
paramConstraintStart byte = '<' // start of type constraint for a parameter
paramConstraintEnd byte = '>' // end of type constraint for a parameter
Expand Down Expand Up @@ -161,7 +161,7 @@ func RoutePatternMatch(path, pattern string, cfg ...Config) bool {
}
// Strict routing, remove trailing slashes
if !config.StrictRouting && len(patternPretty) > 1 {
patternPretty = strings.TrimRight(patternPretty, "/")
patternPretty = utils.TrimRight(patternPretty, '/')
}

parser := parseRoute(patternPretty)
Expand Down Expand Up @@ -233,7 +233,7 @@ func addParameterMetaInfo(segs []*routeSegment) []*routeSegment {
} else {
comparePart = segs[i].Const
if len(comparePart) > 1 {
comparePart = strings.TrimRight(comparePart, slashDelimiterStr)
comparePart = utils.TrimRight(comparePart, slashDelimiterStr)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions redirect.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,10 +249,10 @@ func (r *Redirect) parseAndClearFlashMessages() {
for {
commaPos = findNextNonEscapedCharsetPosition(cookieValue, []byte(CookieDataSeparator))
if commaPos == -1 {
r.c.redirectionMessages = append(r.c.redirectionMessages, strings.Trim(cookieValue, " "))
r.c.redirectionMessages = append(r.c.redirectionMessages, utils.Trim(cookieValue, ' '))
break
}
r.c.redirectionMessages = append(r.c.redirectionMessages, strings.Trim(cookieValue[:commaPos], " "))
r.c.redirectionMessages = append(r.c.redirectionMessages, utils.Trim(cookieValue[:commaPos], ' '))
cookieValue = cookieValue[commaPos+1:]
}

Expand Down
Loading

1 comment on commit fadedcb

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: fadedcb Previous: 87bb93e Ratio
Benchmark_Middleware_BasicAuth - B/op 80 B/op 48 B/op 1.67
Benchmark_Middleware_BasicAuth - allocs/op 5 allocs/op 3 allocs/op 1.67
Benchmark_Middleware_BasicAuth_Upper - B/op 80 B/op 48 B/op 1.67
Benchmark_Middleware_BasicAuth_Upper - allocs/op 5 allocs/op 3 allocs/op 1.67
Benchmark_CORS_NewHandler - B/op 16 B/op 0 B/op +∞
Benchmark_CORS_NewHandler - allocs/op 1 allocs/op 0 allocs/op +∞
Benchmark_CORS_NewHandlerSingleOrigin - B/op 16 B/op 0 B/op +∞
Benchmark_CORS_NewHandlerSingleOrigin - allocs/op 1 allocs/op 0 allocs/op +∞
Benchmark_CORS_NewHandlerPreflight - B/op 104 B/op 0 B/op +∞
Benchmark_CORS_NewHandlerPreflight - allocs/op 5 allocs/op 0 allocs/op +∞
Benchmark_CORS_NewHandlerPreflightSingleOrigin - B/op 104 B/op 0 B/op +∞
Benchmark_CORS_NewHandlerPreflightSingleOrigin - allocs/op 5 allocs/op 0 allocs/op +∞
Benchmark_CORS_NewHandlerPreflightWildcard 1047 ns/op 104 B/op 5 allocs/op 691 ns/op 0 B/op 0 allocs/op 1.52
Benchmark_CORS_NewHandlerPreflightWildcard - ns/op 1047 ns/op 691 ns/op 1.52
Benchmark_CORS_NewHandlerPreflightWildcard - B/op 104 B/op 0 B/op +∞
Benchmark_CORS_NewHandlerPreflightWildcard - allocs/op 5 allocs/op 0 allocs/op +∞
Benchmark_Middleware_CSRF_Check - allocs/op 11 allocs/op 7 allocs/op 1.57
Benchmark_Middleware_CSRF_GenerateToken - B/op 511 B/op 326 B/op 1.57
Benchmark_Middleware_CSRF_GenerateToken - allocs/op 10 allocs/op 6 allocs/op 1.67

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.