-
Notifications
You must be signed in to change notification settings - Fork 2
/
shortener.go
61 lines (53 loc) · 1.21 KB
/
shortener.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
package main
import (
"bytes"
"io/ioutil"
"log"
"math/rand"
"strings"
"time"
)
// shortener creates short strings based on the words it was initialised with
type shortener struct {
wordsSlice [][]string
existing StringStore
}
func (s shortener) getShortURL() string {
var url string
var err error
for err == nil {
url = s.createRandomString()
_, err = s.existing.Get(url)
if err == nil {
log.Printf("Created shortlink %s but was already present in the map\n", url)
}
}
return url
}
func (s shortener) createRandomString() string {
var bytes bytes.Buffer
for _, words := range s.wordsSlice {
bytes.WriteString(words[rand.Intn(len(words))])
}
return bytes.String()
}
func newShortener(existing StringStore, files []string) (shortener, error) {
rand.Seed(time.Now().UnixNano())
wordsSlice := make([][]string, len(files))
for i, file := range files {
words, err := readWords(file)
if err != nil {
return shortener{}, err
}
wordsSlice[i] = words
}
return shortener{wordsSlice, existing}, nil
}
func readWords(filename string) ([]string, error) {
d, err := ioutil.ReadFile(filename)
if err != nil {
return []string{}, err
}
words := strings.Split(string(d), "\n")
return words, nil
}