-
Notifications
You must be signed in to change notification settings - Fork 3
/
uuid.go
52 lines (43 loc) · 937 Bytes
/
uuid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package rand
import "github.com/google/uuid"
import (
"io/ioutil"
"os"
)
// NewUUID returns a uuid string
// format:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
func UUID(random bool) string {
if !random {
key, err := uuid.NewUUID() //按时间戳生成uuid
if err != nil {
return ""
}
return key.String()
}
return uuid.New().String() //随机生成uuid
}
// WriteUUIDToFile return a uuid string and write to file
func UUIDFile(fpath string) (string, error) {
_, err := os.Stat(fpath)
if err != nil && !os.IsExist(err) {
key := uuid.New().String()
if err := ioutil.WriteFile(fpath, []byte(key), 0777); err != nil {
return "", err
}
return key, nil
}
fp, err := os.Open(fpath)
if err != nil {
return "", err
}
defer fp.Close()
data, err := ioutil.ReadAll(fp)
if err != nil {
return "", err
}
key := string(data)
if _, err := uuid.Parse(key); err != nil {
return "", err
}
return key, nil
}