-
Notifications
You must be signed in to change notification settings - Fork 0
/
register.go
96 lines (84 loc) · 2.07 KB
/
register.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
package handlers
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"github.com/skycoop/gophercises/urlshort/urlregistry"
"net/http"
"net/url"
)
type RegisterHandler struct {
registry urlregistry.UrlRegistry
}
type request struct {
Url string `json:"url"`
}
type response struct {
Guid string `json:"guid"`
}
func (h *RegisterHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var req request
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
log.WithField("error", err).Debug("Received invalid JSON")
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
parsedUrl, err := url.Parse(req.Url)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"url": req.Url,
}).Debug("Error when attempting to parse the URL")
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
if !parsedUrl.IsAbs() {
log.WithFields(log.Fields{
"error": err,
"url": parsedUrl,
}).Debug("Provided url is not absolute")
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
switch parsedUrl.Scheme {
case "http":
break
case "https":
break
default:
log.WithFields(log.Fields{
"error": err,
"url": parsedUrl,
}).Debug("Provided url has an invalid scheme")
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
guid, err := h.registry.Register(parsedUrl.String())
if err != nil {
log.WithFields(log.Fields{
"error": err,
"url": req.Url,
}).Error("Error while registering new URL")
panic(http.ErrAbortHandler)
}
res, err := json.Marshal(response{Guid: guid.String()})
if err != nil {
log.WithFields(log.Fields{
"error": err,
"guid": guid,
}).Error("Error while marshalling JSON")
panic(http.ErrAbortHandler)
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(res)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"response": res,
}).Error("Failed to write response")
panic(http.ErrAbortHandler)
}
}
func NewRegisterHandler(r urlregistry.UrlRegistry) *RegisterHandler {
return &RegisterHandler{registry: r}
}