@@ -3,15 +3,16 @@ package uuid
33import (
44 "encoding/base32"
55 "encoding/binary"
6+ "fmt"
67 "net"
78 "os"
89 "sync/atomic"
910 "time"
1011)
1112
1213var (
13- inc uint32
14- buf = make ([]byte , 16 )
14+ seq uint32
15+ buf = make ([]byte , 14 )
1516)
1617
1718func init () {
@@ -21,19 +22,46 @@ func init() {
2122 if ! i .IP .IsLoopback () {
2223 i4 := i .IP .To4 ()
2324 if len (i4 ) == net .IPv4len {
24- buf [0 ] = i .IP .To4 ()[2 ]
25- buf [1 ] = i .IP .To4 ()[3 ]
25+ buf [4 ] = i .IP .To4 ()[0 ]
26+ buf [5 ] = i .IP .To4 ()[1 ]
27+ buf [6 ] = i .IP .To4 ()[2 ]
28+ buf [7 ] = i .IP .To4 ()[3 ]
2629 break
2730 }
2831 }
2932 }
3033 }
31- binary .LittleEndian .PutUint16 (buf [2 :], uint16 (os .Getpid ()))
34+ binary .LittleEndian .PutUint16 (buf [8 :], uint16 (os .Getpid ()))
3235}
3336
3437//String 生成字符串的uuid
3538func String () string {
36- binary .BigEndian .PutUint64 (buf [4 :], uint64 (time .Now ().Unix ()))
37- binary .BigEndian .PutUint32 (buf [12 :], atomic .AddUint32 (& inc , 1 ))
39+ binary .BigEndian .PutUint32 (buf [0 :], uint32 (time .Now (). UTC ().Unix ()))
40+ binary .BigEndian .PutUint32 (buf [10 :], atomic .AddUint32 (& seq , 1 ))
3841 return base32 .HexEncoding .WithPadding (base32 .NoPadding ).EncodeToString (buf )
3942}
43+
44+ //Decode 解析uuid字符串,返回具体细节.
45+ func Decode (s string ) (ip string , pid int , tm time.Time , seq uint32 , err error ) {
46+ var buf []byte
47+ buf , err = base32 .HexEncoding .WithPadding (base32 .NoPadding ).DecodeString (s )
48+ if err != nil {
49+ return
50+ }
51+
52+ tm = time .Unix (int64 (binary .BigEndian .Uint32 (buf )), 0 )
53+ ip = net .IPv4 (buf [4 ], buf [5 ], buf [6 ], buf [7 ]).String ()
54+ pid = int (binary .LittleEndian .Uint16 (buf [8 :]))
55+ seq = binary .BigEndian .Uint32 (buf [10 :])
56+
57+ return
58+ }
59+
60+ //Info 解析uuid中信息.
61+ func Info (s string ) (string , error ) {
62+ ip , pid , tm , seq , err := Decode (s )
63+ if err != nil {
64+ return "" , err
65+ }
66+ return fmt .Sprintf ("ip:%s pid:%d time:%s sequence:%d" , ip , pid , tm .Format (time .RFC3339 ), seq ), nil
67+ }
0 commit comments