-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
68 lines (56 loc) · 1.5 KB
/
api.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
package api
import (
"encoding/json"
"bytes"
"github.com/davidlu1997/fast-shortener/config"
"github.com/davidlu1997/fast-shortener/model"
"github.com/davidlu1997/fast-shortener/shortener"
"github.com/valyala/fasthttp"
)
// API is the primary interface for fast-shortener
type API struct {
shortener shortener.Shortener
config *config.Configuration
}
// InitAPI creates an API from a given configuration
func InitAPI(config *config.Configuration) *API {
return &API{
shortener: shortener.InitCacheShortener(config),
config: config,
}
}
func (a *API) putLinkHandler(ctx *fasthttp.RequestCtx) {
var link model.Link
if err := json.Unmarshal(ctx.PostBody(), &link); err != nil {
ctx.Error(err.Error(), fasthttp.StatusBadRequest)
}
if err := a.shortener.Put(&link); err != nil {
ctx.Error(err.Error(), fasthttp.StatusBadRequest)
return
}
ctx.SetStatusCode(fasthttp.StatusOK)
}
func (a *API) getLinkHandler(ctx *fasthttp.RequestCtx) {
path := ctx.Path()
key := path[bytes.LastIndexByte(path, '/')+1:]
link := a.shortener.Get(string(key))
if link == nil {
ctx.Error("", fasthttp.StatusNotFound)
return
}
ctx.Redirect(link.URL, fasthttp.StatusFound)
}
func (a *API) okHandler(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(fasthttp.StatusOK)
}
// RequestHandler serves all requests to the API
func (a *API) RequestHandler(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/put":
a.putLinkHandler(ctx)
case "/ok":
a.okHandler(ctx)
default:
a.getLinkHandler(ctx)
}
}