Skip to content

Commit 06416eb

Browse files
committed
add uuid
1 parent c370809 commit 06416eb

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

uuid/uuid.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
}

uuid/uuid_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
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+
}

0 commit comments

Comments
 (0)