Files
hospital-admin-api/utils/mask.go
T
2023-09-12 09:35:32 +08:00

90 lines
2.5 KiB
Go

package utils
import (
"regexp"
"unicode/utf8"
)
// MaskNameStr 用户名掩码
func MaskNameStr(str string, maskType int) string {
if str == "" {
return str
}
// 使用正则表达式判断是否包含中文字符
chinesePattern := "[\u4e00-\u9fa5]+"
isChinese, _ := regexp.MatchString(chinesePattern, str)
// 使用正则表达式判断是否包含英文字母
englishPattern := "[A-Za-z]+"
isEnglish, _ := regexp.MatchString(englishPattern, str)
// 判断是否包含中文字符
if isChinese {
// 按照中文字符计算长度
strLen := utf8.RuneCountInString(str)
if strLen >= 3 {
if maskType == 1 {
// 三个字符或三个字符以上掐头取尾,中间用*代替
firstChar, _ := utf8.DecodeRuneInString(str)
lastChar, _ := utf8.DecodeLastRuneInString(str)
str = string(firstChar) + "*" + string(lastChar)
} else {
// 首字母保留,后两位用*代替
firstChar, _ := utf8.DecodeRuneInString(str)
str = string(firstChar) + "**"
}
} else if strLen == 2 {
// 两个字符
firstChar, _ := utf8.DecodeRuneInString(str)
str = string(firstChar) + "*"
}
} else if isEnglish {
// 按照英文字串计算长度
strLen := utf8.RuneCountInString(str)
if strLen >= 3 {
if maskType == 1 {
// 三个字符或三个字符以上掐头取尾,中间用*代替
firstChar, _ := utf8.DecodeRuneInString(str)
lastChar, _ := utf8.DecodeLastRuneInString(str)
str = string(firstChar) + "*" + string(lastChar)
} else {
// 首字母保留,后两位用*代替
firstChar, _ := utf8.DecodeRuneInString(str)
str = string(firstChar) + "**"
}
} else if strLen == 2 {
// 两个字符
firstChar, _ := utf8.DecodeRuneInString(str)
str = string(firstChar) + "*"
}
}
return str
}
// MaskPhoneStr 手机号、固话加密
// 固话:0510-89754815 0510-8****815
// 手机号:18221234158 18*******58
func MaskPhoneStr(phone string) string {
if phone == "" {
return phone
}
// 使用正则表达式匹配固定电话
phonePattern := `(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)`
isFixedLine := regexp.MustCompile(phonePattern).MatchString(phone)
if isFixedLine {
// 匹配到固定电话
// 替换匹配的部分为固定格式
return regexp.MustCompile(`(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)`).ReplaceAllString(phone, "$1****$2")
} else {
// 匹配到手机号
// 替换匹配的部分为固定格式
return regexp.MustCompile(`(1[0-9]{1})[0-9]{7}([0-9]{2})`).ReplaceAllString(phone, "$1*******$2")
}
}