-
Notifications
You must be signed in to change notification settings - Fork 2
/
handlers.go
95 lines (77 loc) · 1.78 KB
/
handlers.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
package handlers
import (
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/render"
)
const (
urlPad = "padname"
)
// Redirect handle redirects to new pads
func Redirect(s storage, e encoder) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cnt, err := s.NextCounter()
if err != nil {
renderError(w, r, err)
return
}
hash := e.Encode(int64(cnt))
http.Redirect(w, r, "/"+hash, http.StatusFound)
}
}
// Get handle get specific pad
func Get(s storage, t tpl) http.HandlerFunc {
type data struct {
Padname string
Content string
}
return func(w http.ResponseWriter, r *http.Request) {
padname := chi.URLParam(r, urlPad)
content, err := s.Get(padname)
if err != nil {
renderError(w, r, err)
return
}
err = t.Execute(w, data{
Padname: padname,
Content: content,
})
if err != nil {
renderError(w, r, err)
}
}
}
// Raw handle get specific pad in plain text
func Raw(s storage) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
padname := chi.URLParam(r, urlPad)
content, err := s.Get(padname)
if err != nil {
renderError(w, r, err)
return
}
render.Status(r, http.StatusOK)
render.PlainText(w, r, content)
}
}
// Set handle set specific pad
func Set(s storage) http.HandlerFunc {
type response struct {
Message string `json:"message"`
Padname string `json:"padname,omitempty"`
}
return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
renderError(w, r, err)
return
}
padname := chi.URLParam(r, urlPad)
content := r.Form.Get("t")
if err := s.Set(padname, content); err != nil {
renderError(w, r, err)
return
}
render.Status(r, http.StatusOK)
render.JSON(w, r, &response{Message: "ok", Padname: padname})
}
}