forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory.go
52 lines (43 loc) · 1.13 KB
/
factory.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
package main
import (
"net/url"
"github.com/google/uuid"
)
// Generator the type to generate keys(short urls)
type Generator func() string
// DefaultGenerator is the defautl url generator
var DefaultGenerator = func() string {
id, _ := uuid.NewRandom()
return id.String()
}
// Factory is responsible to generate keys(short urls)
type Factory struct {
store Store
generator Generator
}
// NewFactory receives a generator and a store and returns a new url Factory.
func NewFactory(generator Generator, store Store) *Factory {
return &Factory{
store: store,
generator: generator,
}
}
// Gen generates the key.
func (f *Factory) Gen(uri string) (key string, err error) {
// we don't return the parsed url because #hash are converted to uri-compatible
// and we don't want to encode/decode all the time, there is no need for that,
// we save the url as the user expects if the uri validation passed.
_, err = url.ParseRequestURI(uri)
if err != nil {
return "", err
}
key = f.generator()
// Make sure that the key is unique
for {
if v := f.store.Get(key); v == "" {
break
}
key = f.generator()
}
return key, nil
}