Go でUUIDを生成したかったら xid が便利だった!
個人プロダクトの開発中にUUIDを生成したくなったのですが
そんな時に見つけた、簡単にUUIDを生成してくれるGo製のライブラリ
こちらの特徴と使い方をご紹介
特徴
The binary representation of the id is compatible with Mongo 12 bytes Object IDs.
全12bytesで構成されており
4-byte value representing the seconds since the Unix epoch,
3-byte machine identifier,
2-byte process id, and
3-byte counter, starting with a random value.
4bytes はUnix timestamp
3bytes はホスト識別子
2bytes はプロセスのID
3bytes はランダムな値
To validate a base32 xid, expect a 20 chars long, all lowercase sequence of a to v letters and 0 to 9 numbers ([0-9a-v]{20}).
生成される文字列は20文字のlower case
使い方
サンプル
package main import ( "fmt" "github.com/rs/xid" ) func main() { guid := xid.New() uuid := guid.String() fmt.Println(uuid) machine := guid.Machine() pid :=guid.Pid() time := guid.Time() counter := guid.Counter() fmt.Println("machine: %v, pid: %v, time: %v, counter: %v", machine, pid, time, counter) }
とても簡単にUUIDを生成することができました。
ユースケース次第ですが、ぜひ使って見てください。
こちらもどうぞ