-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
StringGeneration.go
75 lines (67 loc) · 1.81 KB
/
StringGeneration.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
package helper
/**
Generates / annotates strings
*/
import (
cryptorand "crypto/rand"
"encoding/base64"
"fmt"
"log"
"math/rand"
"regexp"
)
// A rune array to be used for pseudo-random string generation
var characters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
// Used if unable to generate secure random string. A warning will be output
// to the CLI window
func generateUnsafeId(length int) string {
log.Println("Warning! Cannot generate securely random ID!")
b := make([]rune, length)
for i := range b {
b[i] = characters[rand.Intn(len(characters))]
}
return string(b)
}
// Returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly
func generateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := cryptorand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}
// GenerateRandomString returns a URL-safe, base64 encoded securely generated random string.
func GenerateRandomString(length int) string {
b, err := generateRandomBytes(length + 10)
if err != nil {
return generateUnsafeId(length)
}
result := cleanRandomString(base64.URLEncoding.EncodeToString(b))
if len(result) < length {
return GenerateRandomString(length)
}
return result[:length]
}
// ByteCountSI converts bytes to a human-readable format
func ByteCountSI(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(b)/float64(div), "kMGTPE"[exp])
}
// Removes special characters from string
func cleanRandomString(input string) string {
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
Check(err)
return reg.ReplaceAllString(input, "")
}