File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ package uuid
2+
3+ import (
4+ "encoding/base64"
5+ "encoding/binary"
6+ "net"
7+ "os"
8+ "sync/atomic"
9+ "time"
10+ )
11+
12+ var (
13+ inc uint32
14+ buf = make ([]byte , 16 )
15+ )
16+
17+ func init () {
18+ addrs , _ := net .InterfaceAddrs ()
19+ for _ , addr := range addrs {
20+ if i , ok := addr .(* net.IPNet ); ok {
21+ if ! i .IP .IsLoopback () {
22+ i4 := i .IP .To4 ()
23+ if len (i4 ) == net .IPv4len {
24+ buf [0 ] = i .IP .To4 ()[2 ]
25+ buf [1 ] = i .IP .To4 ()[3 ]
26+ break
27+ }
28+ }
29+ }
30+ }
31+ binary .LittleEndian .PutUint16 (buf [2 :], uint16 (os .Getpid ()))
32+ }
33+
34+ //String 生成字符串的uuid
35+ func String () string {
36+ binary .BigEndian .PutUint64 (buf [4 :], uint64 (time .Now ().Unix ()))
37+ binary .BigEndian .PutUint32 (buf [12 :], atomic .AddUint32 (& inc , 1 ))
38+ return base64 .RawURLEncoding .EncodeToString (buf )
39+ }
Original file line number Diff line number Diff line change 1+ package uuid
2+
3+ import (
4+ "testing"
5+ )
6+
7+ func TestUUID (t * testing.T ) {
8+ for i := 0 ; i < 1000 ; i ++ {
9+ t .Logf ("%s" , String ())
10+ }
11+
12+ }
You can’t perform that action at this time.
0 commit comments