使用 mapstruct 自动生成 dto→po 时,如何自定义 time 格式兼容 Gin?
解读
国内项目普遍把“对外 JSON 字段”与“对内数据库字段”拆成两层:DTO(Data Transfer Object)负责出入参,PO(Persistent Object)负责 ORM。Go 没有 Java 那种注解式 MapStruct,但社区用 mapstructure(mitchellh/mapstructure)+ tag 实现“结构体到结构体”的自动映射。
面试问“自定义 time 格式兼容 Gin”,本质考察三件事:
- Gin 用 json 包序列化,默认 RFC3339;mapstructure 用 reflect,不认 json tag。
- 时间字段在 DTO 里往往是字符串(前端好读),在 PO 里是 time.Time(数据库好存)。
- 必须让两边转换逻辑统一,且零值、空串、时区、精度(秒/毫秒)都能兼容,否则线上必踩坑。
知识点
- Gin 渲染链路:c.JSON → json.Marshal → 只认
json:"xxx"tag。 - mapstructure 解码链路:mapstructure.Decode → 只认
mapstructure:"xxx"tag,且默认用time.Time的UnmarshalText接口。 - 自定义时间类型:给
type CustomTime time.Time实现UnmarshalJSON/UnmarshalText/MarshalJSON/MarshalText四个方法,即可同时被 json 包和 mapstructure 识别。 - 零值处理:前端可能传空串
"",需把空串映射成time.Time{}而不是0001-01-01 00:00:00 +0000 UTC,否则写库会触发sql: Scan error。 - 时区统一:国内业务统一用
Asia/Shanghai,禁止用本地时区,否则 K8s 容器里跑出来的时间差 8 小时。 - 性能:mapstructure 用反射,高并发场景可缓存
DecoderConfig,或预生成转换函数,避免每次reflect.TypeOf。
答案
步骤一:定义“双向通用”的时间类型
type ChinaTime time.Time
const ctLayout = "2006-01-02 15:04:05"
// 用于 Gin 出参
func (ct ChinaTime) MarshalJSON() ([]byte, error) {
t := time.Time(ct)
if t.IsZero() {
return []byte(`""`), nil
}
return []byte(`"` + t.In(cst).Format(ctLayout) + `"`), nil
}
// 用于 Gin 入参
func (ct *ChinaTime) UnmarshalJSON(data []byte) error {
s := strings.Trim(string(data), `"`)
if s == "" || s == "null" {
*ct = ChinaTime(time.Time{})
return nil
}
tt, err := time.ParseInLocation(ctLayout, s, cst)
if err != nil {
return err
}
*ct = ChinaTime(tt)
return nil
}
// 用于 mapstructure 解码(map[string]interface{} → struct)
func (ct *ChinaTime) UnmarshalText(text []byte) error {
return ct.UnmarshalJSON(text)
}
func (ct ChinaTime) MarshalText() ([]byte, error) {
return ct.MarshalJSON()
}
var cst = func() *time.Location {
loc, _ := time.LoadLocation("Asia/Shanghai")
return loc
}()
步骤二:在 DTO 和 PO 里都用 ChinaTime
type UserDTO struct {
Birthday ChinaTime `json:"birthday" mapstructure:"birthday"`
}
type UserPO struct {
Birthday time.Time `gorm:"column:birthday"`
}
步骤三:写转换函数,利用 mapstructure 的 DecodeHook 做类型兜底
func ConvertDTOToPO(dto UserDTO) UserPO {
return UserPO{
Birthday: time.Time(dto.Birthday),
}
}
如果字段很多,可统一用 mapstructure:
var decodeHook = mapstructure.ComposeDecodeHookFunc(
// 把 ChinaTime 直接转 time.Time
func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if f == reflect.TypeOf(ChinaTime{}) && t == reflect.TypeOf(time.Time{}) {
return time.Time(data.(ChinaTime)), nil
}
return data, nil
},
mapstructure.StringToTimeHookFunc(ctLayout),
)
cfg := &mapstructure.DecoderConfig{
DecodeHook: decodeHook,
Result: &po,
}
decoder, _ := mapstructure.NewDecoder(cfg)
_ = decoder.Decode(dto)
步骤四:Gin 接入
func UpdateUser(c *gin.Context) {
var dto UserDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
return
}
po := ConvertDTOToPO(dto)
db.Save(&po)
c.JSON(http.StatusOK, dto) // 出参仍用 DTO,时间格式自动按 ChinaTime 规则
}
这样,前端看到的始终是 2006-01-02 15:04:05,数据库里存的是 datetime(3) 类型,零值空串不会抛异常,时区固定在东八区,mapstructure 和 Gin 两端完全打通。
拓展思考
- 如果接口要兼容“时间戳秒”、“时间戳毫秒”、“RFC3339”三种格式,可把
UnmarshalJSON写成多轮try parse,并在文档里明确优先级;线上建议加strict=true开关,灰度阶段打开,防止脏数据。 - 高并发场景可预生成
mapstructure.Decoder对象池,避免每次NewDecoder反射分配;或者弃用 mapstructure,用代码生成工具(如github.com/ulule/deepcopier)在编译期生成dto2po函数,性能接近手写。 - 微服务内部链路如果走 gRPC,时间字段统一用
google.protobuf.Timestamp,再写一层proto→po的转换,避免 HTTP 与 RPC 两套时间格式。 - 单元测试必须覆盖“空串”、“非法格式”、“跨年时间”、“夏令时边缘”、“数据库零值”五种场景,用
testify的assert.Equal校验序列化前后字符串,防止上线后 DBA 反馈“时间多了 8 小时”。