-
Notifications
You must be signed in to change notification settings - Fork 5
/
storage.go
79 lines (62 loc) · 1.91 KB
/
storage.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
// Package storages allows multiple implementation on how to store URLs as shorter names and retrieve them later.
//
// There are currently two types of storage layers, Named and Unnamed.
// Named storage layers allow the user to provide a short name and a URL
// Unnamed storage layers only accept the URL to store
package storage
import (
"errors"
"net/url"
"strings"
)
type Storage interface {
// Load(string) takes a short URL and returns the original full URL by retrieving it from storage
Load(short string) (string, error)
}
type UnnamedStorage interface {
Storage
// Save(string) takes a full URL and returns the short URL after saving it to storage
Save(url string) (string, error)
}
type NamedStorage interface {
Storage
// SaveName takes a short and a url and saves the name to use for saving a url
SaveName(short string, url string) error
}
var SupportedStorageTypes = make(map[string]interface{})
var (
ErrURLEmpty = errors.New("provided URL is of zero length")
ErrShortEmpty = errors.New("provided short name is of zero length")
ErrURLNotAbsolute = errors.New("provided URL is not an absolute URL")
ErrShortNotSet = errors.New("storage layer doens't have a URL for that short code")
ErrShortExhaustion = errors.New("tried to set short, but unable to find a unique shortname within 10 tries")
)
func validateShort(short string) error {
if short == "" {
return ErrShortEmpty
}
return nil
}
func validateURL(rawURL string) (*url.URL, error) {
if rawURL == "" {
return nil, ErrShortEmpty
}
parsedURL, err := url.Parse(rawURL)
if err != nil {
return nil, err
}
if !parsedURL.IsAbs() {
return nil, ErrURLNotAbsolute
}
return parsedURL, nil
}
var normalizingReplacer = strings.NewReplacer(
" ", "",
"-", "",
"_", "",
"/", "",
)
func sanitizeShort(rawShort string) (string, error) {
short := normalizingReplacer.Replace(strings.ToLower(rawShort))
return short, validateShort(short)
}