-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrandom.go
69 lines (48 loc) · 1.63 KB
/
random.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
/*
This file is part of GigaPaste.
GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with GigaPaste. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"database/sql"
"math/rand"
"os"
"strconv"
"time"
)
// we want to avoid ambiguous characters like i, I, l, 1, etc
const charset = "abcdefghkmnpqrstwxyzABCDEFGHJKLMNPQRSTWXYZ23456789"
var seed rand.Source
var random *rand.Rand
func init() {
seed = rand.NewSource(time.Now().UnixNano())
random = rand.New(seed)
}
func GenRandFileName(basePath string, extension string) string {
for {
fileName := strconv.FormatInt(time.Now().UnixMilli(), 10) + genRandString(5) + extension
filePath := basePath + fileName
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return filePath
}
}
}
func GenRandPath(length int, db *sql.DB) string {
for {
randPath := genRandString(6)
var id string
db.QueryRow("SELECT id FROM data WHERE id = ?", randPath).Scan(&id)
if id == "" {
return randPath
}
}
}
func genRandString(length int) string {
result := make([]byte, length)
for i := range result {
result[i] = charset[random.Intn(len(charset))]
}
return string(result)
}