-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
60 lines (48 loc) · 1.01 KB
/
generator.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
package main
import (
"fmt"
"log"
"math/rand"
"strconv"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
type GeneratorFunc func(n int) string
const (
GeneratorString = "string"
GeneratorInt = "int"
)
var (
generator = map[string]GeneratorFunc{
GeneratorString: generateString,
GeneratorInt: generateInt,
}
letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
)
func generate(tokens []string) string {
if len(tokens) != 2 {
log.Println("error: invalid number of arguments in generator")
return ""
}
if gen, ok := generator[tokens[0]]; ok {
val, err := strconv.Atoi(tokens[1])
if err != nil {
log.Println("error: ", err)
}
return gen(val)
}
log.Println("error: specified generator not found")
return ""
}
func generateString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func generateInt(n int) string {
return fmt.Sprintf("%d", rand.Int63n(1e16))[0:n]
}