forked from thomasdesr/go-shorten
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inmem.go
108 lines (84 loc) · 1.69 KB
/
inmem.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package storage
import (
"encoding/json"
"fmt"
"sync"
"github.com/pkg/errors"
)
func init() {
SupportedStorageTypes["Inmem"] = new(interface{})
}
type Inmem struct {
RandLength int
m map[string]string
mu sync.RWMutex
}
func (s Inmem) String() string {
j := struct {
RandLength int
InnerMap map[string]string
}{s.RandLength, s.m}
b, err := json.Marshal(j)
if err != nil {
return fmt.Sprintf("%#v", s)
}
return string(b)
}
func NewInmem(randLength int) (*Inmem, error) {
s := &Inmem{
RandLength: randLength,
m: make(map[string]string),
}
return s, nil
}
func NewInmemFromMap(randLength int, initialShorts map[string]string) (*Inmem, error) {
s, _ := NewInmem(randLength)
for k, v := range initialShorts {
if err := s.SaveName(k, v); err != nil {
return nil, errors.Wrap(err, "failed to save initial short")
}
}
return s, nil
}
func (s *Inmem) Save(url string) (string, error) {
if _, err := validateURL(url); err != nil {
return "", err
}
var code string
s.mu.Lock()
defer s.mu.Unlock()
for i := 0; i < 10; i++ {
code = getRandomString(s.RandLength)
if _, ok := s.m[code]; !ok {
s.m[code] = url
return code, nil
}
}
return "", ErrShortExhaustion
}
func (s *Inmem) SaveName(rawShort string, url string) error {
short, err := sanitizeShort(rawShort)
if err != nil {
return err
}
if _, err := validateURL(url); err != nil {
return err
}
s.mu.Lock()
s.m[short] = url
s.mu.Unlock()
return nil
}
func (s *Inmem) Load(rawShort string) (string, error) {
short, err := sanitizeShort(rawShort)
if err != nil {
return "", err
}
s.mu.Lock()
url, ok := s.m[short]
s.mu.Unlock()
if !ok {
return "", ErrShortNotSet
}
return url, nil
}