util: improve mask key function and add tests

This commit is contained in:
c9s 2022-01-16 23:45:33 +08:00
parent abee20acbf
commit 1b06712d90
2 changed files with 54 additions and 3 deletions

View File

@ -13,8 +13,17 @@ func StringSliceContains(slice []string, needle string) bool {
}
func MaskKey(key string) string {
maskKey := key[0:5]
maskKey += strings.Repeat("*", len(key)-1-5-5)
maskKey += key[len(key)-5-1:]
if len(key) == 0 {
return "{empty}"
}
h := len(key) / 3
if h > 5 {
h = 5
}
maskKey := key[0:h]
maskKey += strings.Repeat("*", len(key)-h*2)
maskKey += key[len(key)-h:]
return maskKey
}

42
pkg/util/string_test.go Normal file
View File

@ -0,0 +1,42 @@
package util
import "testing"
func TestMaskKey(t *testing.T) {
type args struct {
key string
}
tests := []struct {
name string
args args
want string
}{
{
name: "key length more than 5",
args: args{key: "abcdefghijklmnopqr"},
want: "abcde********nopqr",
},
{
name: "key length less than 10",
args: args{key: "12345678"},
want: "12****78",
},
{
name: "even",
args: args{key: "1234567"},
want: "12***67",
},
{
name: "empty",
args: args{key: ""},
want: "{empty}",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := MaskKey(tt.args.key); got != tt.want {
t.Errorf("MaskKey() = %v, want %v", got, tt.want)
}
})
}
}