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

Improve the https scheme matching #508

Merged
merged 4 commits into from
Dec 16, 2024
Merged

Improve the https scheme matching #508

merged 4 commits into from
Dec 16, 2024

Conversation

ryoii
Copy link
Contributor

@ryoii ryoii commented Jul 24, 2023

httpsRegexp     = regexp.MustCompile(`^https:\/\/`)

if !httpsRegexp.MatchString(req.URL.String()) {
	req.URL, err = url.Parse("https://" + r.Host + req.URL.String())
}

There is some code like above. In this case, it is a little bit inappropriate to use the regular expression. This regular expression is used to determine whether the url starts with https scheme. Here, a simple HasPrefix is fine

I write a benchmark to show this.

var httpsRegexp = regexp.MustCompile(`^https:\/\/`)

// BenchmarkMatch-12       11180230                99.44 ns/op
func BenchmarkMatch(b *testing.B) {
	b.Run("use-regex", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			httpsRegexp.MatchString("https://abc.abc.abc")
		}
	})

	b.Run("use-prefix", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			strings.HasPrefix("https://abc.abc.abc", "https")
		}
	})
}

// BenchmarkMatch
// BenchmarkMatch/use-regex
// BenchmarkMatch/use-regex-12             11810976               100.2 ns/op
// BenchmarkMatch/use-prefix
// BenchmarkMatch/use-prefix-12            347787476                3.451 ns/op
// PASS

It seems better.

@ErikPelli
Copy link
Collaborator

Thanks

@ErikPelli ErikPelli merged commit e85c60b into elazarl:master Dec 16, 2024
1 check passed
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 this pull request may close these issues.

2 participants