oklog / ulid

Universally Unique Lexicographically Sortable Identifier (ULID) in Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add the Encoder and Decoder for gob encoding

Xumeiquer opened this issue · comments

It would be interesting to add the capacity to be encoded and decoded using the gob encoding package.

This is already possible.

package main

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"time"

	"github.com/oklog/ulid"
)

func main() {
	now := time.Now()
	fmt.Printf("Now: %s\n", now.Format(time.RFC3339Nano))

	var id ulid.ULID
	id.SetTime(ulid.Timestamp(now))
	fmt.Printf("ID: %s\n", id)

	var buf bytes.Buffer
	gob.NewEncoder(&buf).Encode(id)
	fmt.Printf("Encoded: %x\n", buf.String())

	var res ulid.ULID
	gob.NewDecoder(&buf).Decode(&res)
	fmt.Printf("Decoded: %s\n", res)

	var (
		msec = res.Time()
		sec  = msec / 1e3
		rem  = msec % 1e3
		nsec = rem * 1e6
		t    = time.Unix(int64(sec), int64(nsec))
	)
	fmt.Printf("Decoded time component: %s\n", t.Format(time.RFC3339Nano))
}