MaskSecret masks the middle of a secret string, revealing a small prefix and suffix for identification. The number of characters revealed scales with string length.
(s string)
| 4 | // prefix and suffix for identification. The number of characters |
| 5 | // revealed scales with string length. |
| 6 | func MaskSecret(s string) string { |
| 7 | if s == "" { |
| 8 | return "" |
| 9 | } |
| 10 | |
| 11 | runes := []rune(s) |
| 12 | reveal := revealLength(len(runes)) |
| 13 | |
| 14 | if len(runes) <= reveal*2 { |
| 15 | return "..." |
| 16 | } |
| 17 | |
| 18 | prefix := string(runes[:reveal]) |
| 19 | suffix := string(runes[len(runes)-reveal:]) |
| 20 | return prefix + "..." + suffix |
| 21 | } |
| 22 | |
| 23 | // revealLength returns the number of runes to show at each end. |
| 24 | func revealLength(n int) int { |