-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
248 lines (221 loc) · 4.22 KB
/
main.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package main
import (
"fmt"
"html/template"
"net/http"
"os"
"strings"
"time"
"github.com/go-redis/cache/v8"
"github.com/go-redis/redis/v8"
"github.com/google/uuid"
)
func main() {
// Load settings:
// ---
port := os.Getenv("PORT")
if len(port) == 0 {
port = "3000"
}
addr := ":" + port
baseURL := os.Getenv("BASE_URL")
if len(baseURL) == 0 {
baseURL = fmt.Sprintf("http://localhost:%s", port)
}
redisURL := os.Getenv("REDIS_URL")
if len(redisURL) == 0 {
redisURL = "redis://:@localhost:6379/1"
}
// Bootstrap:
// ---
redisOptions, err := redis.ParseURL(redisURL)
if err != nil {
panic(err)
}
redisClient := redis.NewClient(redisOptions)
defer redisClient.Close()
redisCache := cache.New(&cache.Options{
Redis: redisClient,
})
server := &Server{
BaseURL: baseURL,
RedisCache: redisCache,
}
// Start web server:
// ---
fmt.Printf("Starting web server, listening on %s\n", addr)
err = http.ListenAndServe(addr, server)
if err != nil {
panic(err)
}
}
type Note struct {
Data []byte
Destruct bool
}
type Server struct {
BaseURL string
RedisCache *cache.Cache
}
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
}
s.notFound(w, r)
}
func (s *Server) notFound(
w http.ResponseWriter,
r *http.Request,
) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Not Found"))
}
func (s *Server) badRequest(
w http.ResponseWriter,
r *http.Request,
statusCode int,
message string,
) {
w.WriteHeader(statusCode)
w.Write([]byte(message))
}
func (s *Server) serverError(
w http.ResponseWriter,
r *http.Request,
) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Ops something went wrong. Please check the server logs."))
}
func (s *Server) renderTemplate(
w http.ResponseWriter,
r *http.Request,
data interface{},
name string,
files ...string,
) {
t := template.Must(template.ParseFiles(files...))
err := t.ExecuteTemplate(w, name, data)
if err != nil {
panic(err)
}
}
func (s *Server) renderMessage(
w http.ResponseWriter,
r *http.Request,
title string,
paragraphs ...interface{},
) {
s.renderTemplate(
w, r,
struct {
Title string
Paragraphs []interface{}
}{
Title: title,
Paragraphs: paragraphs,
},
"layout",
"dist/layout.html",
"dist/message.html",
)
}
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 := false
ttl := time.Hour * 24
if form.Get("ttl") == "untilRead" {
destruct = true
ttl = ttl * 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)
s.renderMessage(
w, r,
"Note was successfully created",
template.HTML(
fmt.Sprintf("<a href='%s'>%s</a>", noteURL, noteURL)))
}
func (s *Server) handleGET(
w http.ResponseWriter,
r *http.Request,
) {
path := r.URL.Path
if path == "/" {
s.renderTemplate(
w, r, nil,
"layout",
"dist/layout.html",
"dist/index.html")
return
}
noteID := strings.TrimPrefix(path, "/")
ctx := r.Context()
note := &Note{}
err := s.RedisCache.GetSkippingLocalCache(
ctx,
noteID,
note)
if err != nil {
s.badRequest(
w, r,
http.StatusNotFound,
fmt.Sprintf("Note with ID %s does not exist.", noteID))
return
}
if note.Destruct {
err := s.RedisCache.Delete(ctx, noteID)
if err != nil {
fmt.Println(err)
s.serverError(w, r)
return
}
}
w.WriteHeader(http.StatusOK)
w.Write(note.Data)
}