forked from cloudpatron/cloudpatron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
80 lines (75 loc) · 1.63 KB
/
utils.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"crypto/rand"
"io/ioutil"
"math/big"
"os"
"path/filepath"
)
func GenerateNumericID() (string, error) {
chars := "1234567890"
str := ""
length := 9
for i := 1; i <= length; i++ {
rnum, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
return "", err
}
c := string(chars[rnum.Int64()])
str += c
}
return str, nil
}
func GenerateRandom(length int) string {
chars := "abcdefghjkrtvxyz2346789"
str := ""
for i := 1; i <= length; i++ {
rnum, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
panic(err)
}
c := string(chars[rnum.Int64()])
str += c
}
return str
}
func GenerateID(prefix string) (string, error) {
// Potentially confusing, so exclude:
// Look similar: 1 I l
// Look similar: 0 O
// Look similar: p q
// Look similar: 5 S
// Sound similar: U W
// Sound similar: M N
length := 12 - len(prefix)
chars := "abcdefghjkrtvxyz2346789"
str := ""
for i := 1; i <= length; i++ {
rnum, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
return "", err
}
c := string(chars[rnum.Int64()])
str += c
}
return prefix + str, nil
}
func Overwrite(filename string, data []byte, perm os.FileMode) error {
f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename)+".tmp")
if err != nil {
return err
}
if _, err := f.Write(data); err != nil {
return err
}
if err := f.Sync(); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
if err := os.Chmod(f.Name(), perm); err != nil {
return err
}
return os.Rename(f.Name(), filename)
}