time_as_int64_codec.go 647 B

123456789101112131415161718192021222324252627
  1. package extra
  2. import (
  3. "github.com/json-iterator/go"
  4. "unsafe"
  5. "time"
  6. )
  7. // keep epoch milliseconds
  8. func RegisterTimeAsInt64Codec() {
  9. jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{})
  10. }
  11. type timeAsInt64Codec struct {
  12. }
  13. func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
  14. ts := *((*time.Time)(ptr))
  15. return ts.UnixNano() == 0
  16. }
  17. func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
  18. ts := *((*time.Time)(ptr))
  19. stream.WriteInt64(ts.UnixNano())
  20. }
  21. func (codec *timeAsInt64Codec) EncodeInterface(val interface{}, stream *jsoniter.Stream) {
  22. jsoniter.WriteToStream(val, stream, codec)
  23. }