-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshort.go
91 lines (72 loc) · 2.43 KB
/
short.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
package lil
import (
"context"
"net/url"
"time"
)
var (
ErrEmptyURL = Errorf(EINVALID, "Missing URL.")
ErrEmptyKey = Errorf(EINVALID, "Missing Key.")
ErrEmptyOwner = Errorf(EINVALID, "Missing owner.")
ErrInvalidURLScheme = Errorf(EINVALID, "Invalid URL scheme. Only http and https are supported.")
)
// Short defines a shortened URL.
type Short struct {
// URL stores the original URL.
URL url.URL `json:"url"`
// Key stores the key needed to retrieve the original URL.
Key string `json:"key"`
Owner *User `json:"-"`
OwnerID int `json:"-"`
// CreatedAt and UpdatedAt get filled by the service.
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// ShortService represents a service for managing Shorts.
type ShortService interface {
// Retrieves a single Short by Key. Returns ENOTFOUND if the Short
// object does not exist. Returns EUNAUTHORIZED if the Short does not
// belong to the user.
FindShortByKey(ctx context.Context, key string) (*Short, error)
// Retrieves a single Short by Key. Returns ENOTFOUND if the Short
// object does not exist. Does not check if the Short does belong
// to the user.
SearchShort(ctx context.Context, key string) (*Short, error)
// Retrieves a list of Shorts based on a filter. Returns a count of the
// matching objects that may be different from the actual count of objects
// returned (if you have set the "Limit" field).
FindShorts(ctx context.Context, filter ShortFilter) ([]*Short, int, error)
// Creates a new Short.
CreateShort(ctx context.Context, short *Short) error
// Permanently removes a Short. Returns a ENOTFOUND if the key
// does not belong to any Short.
DeleteShort(ctx context.Context, key string) error
}
// ShortFilter represents a filter used by FindShorts().
type ShortFilter struct {
Key *string `json:"key"`
URL *url.URL `json:"url"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}
// Validate returns an error if Short has invalid fields.
// Only performs basic validation.
func (s *Short) Validate() error {
if s.URL.String() == "" {
return ErrEmptyURL
}
if s.URL.Scheme != "https" && s.URL.Scheme != "http" {
return ErrInvalidURLScheme
}
if s.Key == "" {
return ErrEmptyKey
}
if s.OwnerID == 0 {
return ErrEmptyOwner
}
return nil
}
// Only the short owner can delete the short.
func CanEditShort(ctx context.Context, short *Short) bool {
return short.OwnerID == UserIDFromContext(ctx)
}