Skip to content

Instantly share code, notes, and snippets.

@mstoykov
Last active September 25, 2019 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mstoykov/280f527fdf0834d275d40b5133064e4b to your computer and use it in GitHub Desktop.
Save mstoykov/280f527fdf0834d275d40b5133064e4b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/url"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func A(u *url.URL, out string) string {
if u != nil && u.User != nil {
// mask user credentials
creds := fmt.Sprintf("%s@", u.User.String())
mask := "****@"
_, passSet := u.User.Password()
if passSet {
mask = fmt.Sprintf("****:%s", mask)
}
return strings.Replace(out, creds, mask, 1)
}
return out
}
var badCredential = url.UserPassword("USER", "PASS")
func B(u *url.URL, out string) string {
if u != nil && u.User != nil {
var tmp = u.User
u.User = badCredential
out = u.String()
u.User = tmp
}
return out
}
func C(u *url.URL, out string) string {
if u != nil && u.User != nil {
schemeIndex := strings.Index(out, "://")
atIndex := strings.Index(out, "@")
if _, passwordOk := u.User.Password(); passwordOk {
out = out[:schemeIndex+3] + "****:****" + out[atIndex:]
} else {
out = out[:schemeIndex+3] + "****" + out[atIndex:]
}
}
return out
}
func BenchmarkA(b *testing.B) {
benchF(b, A)
}
func BenchmarkB(b *testing.B) {
benchF(b, B)
}
func BenchmarkC(b *testing.B) {
benchF(b, C)
}
func benchF(b *testing.B, f func(*url.URL, string) string) {
var rawURL = "https://pesho:joro@example.com"
b.RunParallel(func(pb *testing.PB) {
var u, _ = url.Parse(rawURL)
for pb.Next() {
f(u, rawURL)
// assert.Equal(b, "https://****:****@example.com", f(u, rawURL))
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment