-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
141 lines (124 loc) · 2.32 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package main
import (
"fmt"
"github.com/go-redis/cache/v8"
"github.com/google/uuid"
"html/template"
"net/http"
"strings"
"time"
)
func (s *Server) ServeHTTP(
w http.ResponseWriter,
r *http.Request,
) {
if r.Method == "GET" || r.Method == "HEAD" {
s.handleGET(w, r)
return
}
if r.Method == "POST" && r.URL.Path == "/" {
s.handlePOST(w, r)
return
}
}
func (s *Server) handlePOST(
w http.ResponseWriter,
r *http.Request,
) {
mediaType := r.Header.Get("Content-Type")
if mediaType != "application/x-www-form-urlencoded" {
s.badRequest(
w, r,
http.StatusUnsupportedMediaType,
"Invalid media type posted.")
return
}
err := r.ParseForm()
if err != nil {
s.badRequest(
w, r,
http.StatusBadRequest,
"Invalid form data posted.")
return
}
form := r.PostForm
message := form.Get("message")
destruct := true
ttl := time.Hour * 24 * 365
note := &Note{
Data: []byte(message),
Destruct: destruct,
}
key := uuid.NewString()
err = s.RedisCache.Set(
&cache.Item{
Ctx: r.Context(),
Key: key,
Value: note,
TTL: ttl,
SkipLocalCache: true,
})
if err != nil {
fmt.Println(err)
s.serverError(w, r)
return
}
w.WriteHeader(http.StatusOK)
noteURL := fmt.Sprintf("%s/%s", s.BaseURL, key)
data := struct {
NoteURL string
}{
NoteURL: noteURL,
}
s.renderTemplate(w, r, data, "layout", "html/layout.html", "html/success.html")
}
func (s *Server) handleGET(
w http.ResponseWriter,
r *http.Request,
) {
path := r.URL.Path
if path == "/" {
s.renderTemplate(
w, r, nil,
"layout",
"html/layout.html",
"html/index.html")
return
}
noteID := strings.TrimPrefix(path, "/")
ctx := r.Context()
note := &Note{}
err := s.RedisCache.GetSkippingLocalCache(
ctx,
noteID,
note)
if err != nil {
s.notFound(
w, r,
"Note Not Found",
fmt.Sprintf("Note with ID %s does not exist.", noteID))
return
}
data := template.HTML(string(note.Data))
if note.Destruct {
err := s.RedisCache.Delete(ctx, noteID)
if err != nil {
fmt.Println(err)
s.serverError(w, r)
return
}
}
w.WriteHeader(http.StatusOK)
s.renderTemplate(
w, r, struct {
Title string
NoteContent template.HTML
}{
Title: "Note",
NoteContent: data,
},
"layout",
"html/layout.html",
"html/note.html")
return
}