59 lines
1.1 KiB
Go
59 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// CustomTime 自定义时间类型
|
|
type CustomTime time.Time
|
|
|
|
const timeLayout = "2006-01-02 15:04:05"
|
|
|
|
func (t CustomTime) MarshalJSON() ([]byte, error) {
|
|
return json.Marshal(time.Time(t).Format(timeLayout))
|
|
}
|
|
|
|
func (t *CustomTime) UnmarshalJSON(data []byte) error {
|
|
var timeStr string
|
|
if err := json.Unmarshal(data, &timeStr); err != nil {
|
|
return err
|
|
}
|
|
val, err := time.Parse(timeLayout, timeStr)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
*t = CustomTime(val)
|
|
return nil
|
|
}
|
|
|
|
// Mobile 手机号脱敏
|
|
type Mobile string
|
|
|
|
func (m Mobile) MarshalJSON() ([]byte, error) {
|
|
num := string(m)
|
|
if len(num) == 11 {
|
|
return json.Marshal(num[:3] + "****" + num[7:])
|
|
}
|
|
return json.Marshal(num)
|
|
}
|
|
|
|
// UserDTO 数据传输对象
|
|
type UserDTO struct {
|
|
Name string `json:"name"`
|
|
Phone Mobile `json:"phone"`
|
|
CreateAt CustomTime `json:"create_at"`
|
|
}
|
|
|
|
func main() {
|
|
dto := UserDTO{
|
|
Name: "bulma",
|
|
Phone: Mobile("10012345678"),
|
|
CreateAt: CustomTime(time.Now()),
|
|
}
|
|
data, _ := json.MarshalIndent(dto, "", " ")
|
|
fmt.Println("\n=== 自定义序列化结果 ===")
|
|
fmt.Println(string(data))
|
|
}
|