jsoniter 在 Gin 中开启兼容模式后,如何解决 time.Time 序列化精度丢失?

解读

国内生产环境普遍把 jsoniter 作为 Gin 的 JSON 引擎,以换取 30% 以上的吞吐提升。
开启 jsoniter.ConfigCompatibleWithStandardLibrary 后,jsoniter 为了与 encoding/json 行为一致,默认把 time.Time 当成「字符串」处理,且只保留到秒级(2006-01-02 15:04:05),导致毫秒/纳秒/时区信息全部丢弃。
面试时,面试官真正想确认的是:

  1. 你是否知道「精度丢失」根因在 jsoniter 的 TimeAsInt64Codec;
  2. 能否在不回退标准库的前提下,用「自定义 codec」或「自定义类型」两种官方推荐手段把精度找回来;
  3. 是否了解 Gin 的 Render 替换机制,能把改动局限在框架层,对业务代码零侵入。

知识点

  1. jsoniter 的 Codec 接口:IsEmpty(ptr unsafe.Pointer) bool、Encode(ptr unsafe.Pointer, stream *jsoniter.Stream)、Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator)。
  2. RegisterTypeEncoder/RegisterTypeDecoder 在首次 init 阶段生效,全局唯一,线程安全。
  3. Gin 的 json 渲染入口:gin.render.JSON,其内部通过 jsoniter.Marshal 完成序列化;替换掉 jsoniter.Config 即可无痛生效。
  4. time.Time 的三种精度表达:秒(Unix)、毫秒(UnixMilli)、纳秒(UnixNano);RFC3339Nano 带时区,是最常用的云原生格式。
  5. 兼容模式与性能模式区别:兼容模式保留 ,string 标签行为,性能模式直接绕过反射;生产环境若全链路控制,可切到性能模式再自定义 codec,获得极限吞吐。

答案

步骤一:定义一个全局可复用的 jsoniter API,确保 Gin 与业务逻辑都用同一实例。

var jsonAPI = jsoniter.Config{
    EscapeHTML:                    true,
    SortMapKeys:                   true,
    MarshalFloatWith6Digits:       true,
    ObjectFieldMustBeSimpleString: true,
}.Froze()

步骤二:为 time.Time 注册高精度 codec,采用 RFC3339Nano 字符串形式,保持人类可读与时区信息。

func init() {
    jsonAPI.RegisterTypeEncoder("time.Time", &timeCodec{})
    jsonAPI.RegisterTypeDecoder("time.Time", &timeCodec{})
}

type timeCodec struct{}

func (c *timeCodec) IsEmpty(ptr unsafe.Pointer) bool {
    ts := *((*time.Time)(ptr))
    return ts.IsZero()
}

func (c *timeCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
    ts := *((*time.Time)(ptr))
    if ts.IsZero() {
        stream.WriteNil()
        return
    }
    stream.WriteString(ts.Format(time.RFC3339Nano))
}

func (c *timeCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
    str := iter.ReadString()
    if str == "" {
        return
    }
    ts, err := time.Parse(time.RFC3339Nano, str)
    if err != nil {
        iter.ReportError("time.Time", err.Error())
        return
    }
    *((*time.Time)(ptr)) = ts
}

步骤三:把 Gin 默认的 JSON 渲染器换成上面的 jsonAPI。

func main() {
    gin.MarshalJSON = jsonAPI.Marshal
    gin.UnmarshalJSON = jsonAPI.Unmarshal

    r := gin.New()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{"now": time.Now()})
    })
    r.Run()
}

至此,time.Time 序列化输出为 2023-07-18T15:04:05.999999999+08:00,精度与标准库 RFC3339Nano 完全一致,且性能仍保持 jsoniter 水平;反序列化也能正确还原纳秒与时区。

拓展思考

  1. 如果业务只在内网交换,可以干脆把 time.Time 编码成 UnixNano 的 int64,进一步减少 30% CPU,但需前后端约定一致。
  2. 当微服务使用 gRPC 对外暴露时,建议直接采用 protobuf.Timestamp,避免 HTTP JSON 与 Protobuf 两套时间格式带来的维护成本。
  3. 在 Kubernetes 写 Operator 时,controller-runtime 也使用 jsoniter;同样的注册思路可解决 CRD 状态里 metav1.Time 的精度问题,防止连续 Reconcile 误判。
  4. 若团队已接入 OpenTelemetry,可以把 timeCodec 与 trace.id、span.id 一起封装成统一序列化包,保证日志、链路、接口三处时间戳格式一致,方便 ELK/Loki 聚合。