提交 88b206f3 authored 作者: mooncake9527's avatar mooncake9527

add self-defined type password and mobile

上级 6785fead
package cd
import (
"encoding/xml"
"strings"
"unicode"
)
type Mobile string
func (d *Mobile) MarshalCSV() (string, error) {
if d == nil {
return "", nil
}
return MaskPhone(string(*d)), nil
}
func (d *Mobile) UnmarshalCSV(csv string) error {
*d = Mobile(csv)
return nil
}
// MarshalJSON 实现JSON序列化
func (d *Mobile) MarshalJSON() ([]byte, error) {
if d == nil {
return []byte(`null`), nil
}
return []byte(`"` + MaskPhone(string(*d)) + `"`), nil
}
// UnmarshalJSON 实现JSON反序列化
func (d *Mobile) UnmarshalJSON(data []byte) error {
if string(data) == `null` {
*d = ""
return nil
}
s := strings.Trim(string(data), `"`)
*d = Mobile(s)
return nil
}
// MarshalXML 实现XML序列化
func (d *Mobile) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if d == nil {
return nil
}
return e.EncodeElement(MaskPhone(string(*d)), start)
}
// UnmarshalXML 实现XML反序列化
func (d *Mobile) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error {
var s string
if err := dec.DecodeElement(&s, &start); err != nil {
return err
}
*d = Mobile(s)
return nil
}
// MaskPhone 智能识别手机号格式并脱敏
func MaskPhone(phone string) string {
// 提取纯数字
digits := strings.Map(func(r rune) rune {
if unicode.IsDigit(r) {
return r
}
return -1
}, phone)
switch {
case len(digits) == 8: // 本地8位号码
return digits[:2] + strings.Repeat("*", 4) + digits[6:]
case len(digits) == 11: // 标准11位手机
return digits[:3] + strings.Repeat("*", 4) + digits[7:]
case len(digits) == 12: // 带区号的12位
return digits[:4] + strings.Repeat("*", 4) + digits[8:]
default:
return phone // 其他格式原样返回
}
}
package cd
import (
"encoding/xml"
"strings"
)
type Password string
func (d *Password) MarshalCSV() (string, error) {
if d == nil {
return "******", nil
}
return "******", nil
}
func (d *Password) UnmarshalCSV(csv string) error {
*d = Password(csv)
return nil
}
// MarshalJSON 实现JSON序列化
func (d *Password) MarshalJSON() ([]byte, error) {
if d == nil {
return []byte(`null`), nil
}
return []byte(`"******"`), nil
}
// UnmarshalJSON 实现JSON反序列化
func (d *Password) UnmarshalJSON(data []byte) error {
if string(data) == `null` {
*d = ""
return nil
}
s := strings.Trim(string(data), `"`)
*d = Password(s)
return nil
}
// MarshalXML 实现XML序列化
func (d *Password) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if d == nil {
return nil
}
return e.EncodeElement("******", start)
}
// UnmarshalXML 实现XML反序列化
func (d *Password) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error {
var s string
if err := dec.DecodeElement(&s, &start); err != nil {
return err
}
*d = Password(s)
return nil
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论