使用 mapstruct 自动生成 dto→po 时,如何自定义 time 格式兼容 Gin?

解读

国内项目普遍把“对外 JSON 字段”与“对内数据库字段”拆成两层:DTO(Data Transfer Object)负责出入参,PO(Persistent Object)负责 ORM。Go 没有 Java 那种注解式 MapStruct,但社区用 mapstructure(mitchellh/mapstructure)+ tag 实现“结构体到结构体”的自动映射。
面试问“自定义 time 格式兼容 Gin”,本质考察三件事:

  1. Gin 用 json 包序列化,默认 RFC3339;mapstructure 用 reflect,不认 json tag。
  2. 时间字段在 DTO 里往往是字符串(前端好读),在 PO 里是 time.Time(数据库好存)。
  3. 必须让两边转换逻辑统一,且零值、空串、时区、精度(秒/毫秒)都能兼容,否则线上必踩坑。

知识点

  1. Gin 渲染链路:c.JSON → json.Marshal → 只认 json:"xxx" tag。
  2. mapstructure 解码链路:mapstructure.Decode → 只认 mapstructure:"xxx" tag,且默认用 time.Time 的 UnmarshalText 接口。
  3. 自定义时间类型:给 type CustomTime time.Time 实现 UnmarshalJSON/UnmarshalText/MarshalJSON/MarshalText 四个方法,即可同时被 json 包和 mapstructure 识别。
  4. 零值处理:前端可能传空串 "",需把空串映射成 time.Time{} 而不是 0001-01-01 00:00:00 +0000 UTC,否则写库会触发 sql: Scan error。
  5. 时区统一:国内业务统一用 Asia/Shanghai,禁止用本地时区,否则 K8s 容器里跑出来的时间差 8 小时。
  6. 性能: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 两端完全打通。

拓展思考

  1. 如果接口要兼容“时间戳秒”、“时间戳毫秒”、“RFC3339”三种格式,可把 UnmarshalJSON 写成多轮 try parse,并在文档里明确优先级;线上建议加 strict=true 开关,灰度阶段打开,防止脏数据。
  2. 高并发场景可预生成 mapstructure.Decoder 对象池,避免每次 NewDecoder 反射分配;或者弃用 mapstructure,用代码生成工具(如 github.com/ulule/deepcopier)在编译期生成 dto2po 函数,性能接近手写。
  3. 微服务内部链路如果走 gRPC,时间字段统一用 google.protobuf.Timestamp,再写一层 proto→po 的转换,避免 HTTP 与 RPC 两套时间格式。
  4. 单元测试必须覆盖“空串”、“非法格式”、“跨年时间”、“夏令时边缘”、“数据库零值”五种场景,用 testify 的 assert.Equal 校验序列化前后字符串,防止上线后 DBA 反馈“时间多了 8 小时”。