-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
97 lines (75 loc) · 2.12 KB
/
handler.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
package handlers
import (
"encoding/json"
"fmt"
"github.com/patrick-me/tinyUrl/generators"
"github.com/patrick-me/tinyUrl/storage"
"github.com/valyala/fasthttp"
"strings"
)
type UrlHandler struct {
Storage storage.Storage
Generator generators.URLGenerator
}
func (h *UrlHandler) Router(ctx *fasthttp.RequestCtx) {
if ctx.IsPost() {
switch string(ctx.Path()) {
case "/short":
createShortUrlHandler(ctx, h)
default:
ctx.Error("Unsupported path", fasthttp.StatusNotFound)
}
return
}
if ctx.IsGet() {
getHandler(ctx, h)
return
}
ctx.Error("Unsupported method", fasthttp.StatusMethodNotAllowed)
}
func getHandler(ctx *fasthttp.RequestCtx, h *UrlHandler) {
url := string(ctx.Path()[1:]) // without leading slash
originUrl, err := h.Storage.Get(url)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusNotFound)
_, err2 := fmt.Fprintf(ctx,
"URL not found!\n%q\n", url)
if err2 != nil {
fmt.Println("Error code #122")
return
}
return
}
ctx.Redirect(originUrl, fasthttp.StatusMovedPermanently)
}
func createShortUrlHandler(ctx *fasthttp.RequestCtx, h *UrlHandler) {
body := ctx.PostBody()
var urlRequest *URLRequest
err := json.Unmarshal(body, &urlRequest)
if err != nil {
ctx.Error(fmt.Sprintf("Can't parse url, %q", err), fasthttp.StatusBadRequest)
return
}
if valid, message := isUrlValid(urlRequest.Url); !valid {
ctx.Error(message, fasthttp.StatusBadRequest)
return
}
shortURL := h.Generator.GetRandURL()
for h.Storage.Contains(shortURL) {
shortURL = h.Generator.GetRandURL()
}
h.Storage.Save(shortURL, urlRequest.Url, urlRequest.ExpirationInHours)
data, _ := json.Marshal(&URLResponse{Url: urlRequest.Url, Short: shortURL})
ctx.SetStatusCode(fasthttp.StatusCreated)
ctx.SetBody(data)
}
func isUrlValid(url string) (bool, string) {
url = strings.ToLower(url)
if !strings.HasPrefix(url, "https://") && !strings.HasPrefix(url, "http://") {
return false, fmt.Sprintf("URL should start with http(s)://, %q", url)
}
if strings.Contains(url, "localhost") || strings.Contains(url, "127.0.0.1") {
return false, fmt.Sprintf("URL isn't valid, %q", url)
}
return true, ""
}