Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 utils.Trim wrong result if it should return a empty string #1774

Closed
trim21 opened this issue Feb 13, 2022 · 0 comments · Fixed by #1775
Closed

🐛 utils.Trim wrong result if it should return a empty string #1774

trim21 opened this issue Feb 13, 2022 · 0 comments · Fixed by #1775

Comments

@trim21
Copy link
Contributor

trim21 commented Feb 13, 2022

Fiber version

v2.26.0

Issue description

utils.Trim(" ", ' ') got " " instead of ""

Code snippet

package main_test

import (
	"strings"
	"testing"

	"github.com/gofiber/fiber/v2/utils"
	"github.com/stretchr/testify/assert"
)

func TestShouldBeEmptyString(t *testing.T) {
	assert.Equal(t, "", utils.Trim(" ", ' ')) // this is wrong, result is " "
	assert.Equal(t, "", strings.Trim(" ", " ")) // this is right
}

fix:

// Trim is the equivalent of strings.Trim
func Trim(s string, cutset byte) string {
	i, j := 0, len(s)-1
	for ; i < j; i++ {
		if s[i] != cutset {
			break
		}
	}
	for ; i < j; j-- {
		if s[j] != cutset {
			break
		}
	}

+	if i == j {
+		if s[i] == cutset {
+			return ""
+		}
+	}

	return s[i : j+1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant