github.com/codingeasygo/util@v0.0.0-20231206062002-1ce2f004b7d9/uuid/uuid.go (about) 1 package uuid 2 3 import ( 4 "crypto/md5" 5 "encoding/binary" 6 "encoding/hex" 7 "os" 8 "sync/atomic" 9 "time" 10 ) 11 12 var uuidCounter uint32 = 0 13 14 //New create new uuid 15 func New() string { 16 var b [12]byte 17 // Timestamp, 4 bytes, big endian 18 binary.BigEndian.PutUint32(b[:], uint32(time.Now().Unix())) 19 // Machine, first 3 bytes of md5(hostname) 20 b[4] = MachineID[0] 21 b[5] = MachineID[1] 22 b[6] = MachineID[2] 23 // Pid, 2 bytes, specs don't specify endianness, but we use big endian. 24 pid := os.Getpid() 25 b[7] = byte(pid >> 8) 26 b[8] = byte(pid) 27 // Increment, 3 bytes, big endian 28 i := atomic.AddUint32(&uuidCounter, 1) 29 b[9] = byte(i >> 16) 30 b[10] = byte(i >> 8) 31 b[11] = byte(i) 32 return hex.EncodeToString(b[:]) 33 } 34 35 //MachineID the machine id 36 var MachineID = ReadMachineID() 37 38 //ReadMachineID generates and returns a machine id. 39 // If this function fails to get the hostname it will cause a runtime error. 40 func ReadMachineID() []byte { 41 var sum [3]byte 42 id := sum[:] 43 hostname, _ := os.Hostname() 44 // if err1 != nil { 45 // _, err2 := io.ReadFull(rand.Reader, id) 46 // if err2 != nil { 47 // panic(fmt.Errorf("cannot get hostname: %v; %v", err1, err2)) 48 // } 49 // return id 50 // } 51 hw := md5.New() 52 hw.Write([]byte(hostname)) 53 copy(id, hw.Sum(nil)) 54 return id 55 } 56 57 //MID is machine id 58 func MID() string { 59 return hex.EncodeToString(MachineID) 60 }