提交 389c9a37 authored 作者: mooncake9527's avatar mooncake9527

add idcard

上级 88b206f3
package cd
import (
"database/sql/driver"
"encoding/json"
"encoding/xml"
"fmt"
"unicode/utf8"
)
type IDCard string
// Mask 身份证号遮蔽处理(保留格式中的X)
func (id IDCard) Mask() string {
s := string(id)
length := utf8.RuneCountInString(s)
switch {
case length == 18:
return s[:6] + "********" + s[14:]
case length == 15:
return s[:6] + "******" + s[12:]
default:
return s
}
}
// MarshalJSON 序列化时自动遮蔽敏感信息
func (id IDCard) MarshalJSON() ([]byte, error) {
return json.Marshal(id.Mask())
}
// UnmarshalJSON 反序列化保持原始数据
func (id *IDCard) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
*id = IDCard(s)
return nil
}
// MarshalXML 序列化时自动遮蔽敏感信息
func (id IDCard) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return e.EncodeElement(id.Mask(), start)
}
// UnmarshalXML 反序列化保持原始数据
func (id *IDCard) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var s string
if err := d.DecodeElement(&s, &start); err != nil {
return err
}
*id = IDCard(s)
return nil
}
// MarshalCSV 序列化时自动遮蔽敏感信息
func (id IDCard) MarshalCSV() (string, error) {
return id.Mask(), nil
}
// UnmarshalCSV 反序列化保持原始数据
func (id *IDCard) UnmarshalCSV(csv string) error {
*id = IDCard(csv)
return nil
}
// Scan 数据库读取接口
func (id *IDCard) Scan(value interface{}) error {
if value == nil {
*id = ""
return nil
}
switch v := value.(type) {
case []byte:
*id = IDCard(v)
case string:
*id = IDCard(v)
default:
return fmt.Errorf("无法扫描非string/[]byte类型的值到IDCard")
}
return nil
}
// Value 数据库写入接口
func (id IDCard) Value() (driver.Value, error) {
return string(id), nil
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论