-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
329 lines (283 loc) · 8.77 KB
/
server.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package goodidea
import (
"fmt"
"html/template"
"io"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
)
var tmpl *template.Template
func index(w http.ResponseWriter, r *http.Request) {
tsks, err := getAllTasks(25)
if err != nil {
slog.Error("Could not get all tasks from db", err)
}
err = tmpl.ExecuteTemplate(w, "index.html", tsks)
if err != nil {
slog.Error("Could not execute template", err)
}
}
func listTasks(w http.ResponseWriter, r *http.Request) {
title := r.URL.Query().Get("title")
var err error
var taskList []Task
if title == "" {
taskList, err = getAllTasks(35)
} else {
taskList, err = getSomeTasks(title)
}
if err != nil {
slog.Error("Could not get tasks from db", err)
return
}
err = tmpl.ExecuteTemplate(w, "list-tasks.html", taskList)
if err != nil {
slog.Error("Could not execute template", err)
}
}
// TODO: Handle errors and report them back to the UI
func updateScore(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(mux.Vars(r)["id"], 10, 64)
if err != nil {
slog.Error("Could not parse id", "err", err)
return
}
err = r.ParseForm()
if err != nil {
slog.Error("Error parsing form", "err", err)
return
}
vote := r.FormValue(fmt.Sprintf("scorekeeper%d", id))
var val int8 = 0
switch vote {
case "inc":
val = 1
case "inc2":
val = 2
case "dec":
val = -1
case "dec2":
val = -2
default:
slog.Error("Did not understand the new vote value", "vote", vote)
return
}
score, err := updateTaskScore(uint32(id), val)
if err != nil {
slog.Error("Could not update task score", err)
}
fmt.Fprintf(w, fmt.Sprintf("%d", score))
}
// createTask - recieve a title and body and create a new task in the DB with default values
// return an HTML block of the Task summarized to be displayed on landing page
func createTask(w http.ResponseWriter, r *http.Request) {
//TODO: MultipartReader to transform this to a steam
err := r.ParseMultipartForm(32 << 20) //32MB
if err != nil {
slog.Error("Error parsing form", err)
}
title := r.FormValue("title")
if title == "" {
fmt.Fprintf(w, "<p>Tasks must have a title.</p>")
return
}
body := r.FormValue("details")
taskID, err := addTask(title, body)
if err != nil {
slog.Error("Could not create a new task", "error", err)
fmt.Fprintf(w, "<p>Could not create a new task</p>")
return
}
//On the summary page, don't show an entire task description which may be long
if len(body) > 64 {
body = body[:64]
}
task := Task{
ID: taskID,
Title: title,
Body: &body,
Score: 0,
}
err = tmpl.ExecuteTemplate(w, "make-task.html", task)
if err != nil {
slog.Error("Could not execute template", err)
}
//Add any images which may have been sent along with the form data
fhs, ok := r.MultipartForm.File["taskImgs"] //matches html
if !ok {
return
}
filePaths := make([]string, len(fhs))
for i, fh := range fhs {
f, err := fh.Open()
defer f.Close()
nameComponents := strings.Split(fh.Filename, ".")
if len(nameComponents) != 2 {
slog.Error("Could not find the extension of the uploaded file", "error", err)
return
}
b, err := io.ReadAll(f)
if err != nil {
slog.Error("could not read bytes out of file sent", "error", err)
return
}
//TODO: can the rest of the following be done in a go routine?
m := NewFileManager()
s, err := m.StoreFile(b, nameComponents[1])
if err != nil {
slog.Error("Unable to store images", "task", taskID, "error", err.Error())
return
}
f.Close()
filePaths[i] = s
}
go saveTaskImages(taskID, filePaths)
}
func viewTask(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(mux.Vars(r)["id"], 10, 64)
if err != nil {
slog.Error("Could not parse id", err)
fmt.Fprintf(w, "ERROR! Could not get task ID from request")
return
}
//TODO: Why not get all of the comments for the task in one query?
tsk, err := getTasksByID(uint32(id))
if err != nil {
slog.Error("could not get task by id", "taskID", id, "error", err)
fmt.Fprintf(w, "Error could not get a task with this ID")
return
}
comments, err := getAllTaskComments(uint32(id))
if err != nil {
slog.Error("could not get comments for task", "taskID", id, "error", err)
}
tsk.Comments = comments
err = tmpl.ExecuteTemplate(w, "show-task.html", tsk)
if err != nil {
slog.Error("could not render template for task", "taskID", id, "error", err)
}
}
func markTaskComplete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(mux.Vars(r)["id"], 10, 64)
if err != nil {
slog.Error("Could not parse id", "error", err)
fmt.Fprintf(w, "ERROR! Could not get task ID from request")
return
}
if err := toggleStatus(uint32(id)); err != nil {
slog.Error("Could not mark task complete", "error", err, "id", id)
fmt.Fprintf(w, "<p>ERROR! could not mark complete</p>")
return
}
tsk, err := getTasksByID(uint32(id))
if err != nil {
slog.Error("could not get task by id", "taskID", id, "error", err)
fmt.Fprintf(w, "Error could not get a task with this ID")
return
}
t1 := template.New("status")
t1, err = t1.Parse("<p id='task-status' class='col-start-10'>Status: {{ if . }}Completed{{ else }}Incomplete{{end -}}</p>")
if err != nil {
panic(err)
}
if err = t1.Execute(w, tsk.Status); err != nil {
slog.Error("Could not execute the template for marking a task complete", "taskID", id, "error", err)
fmt.Fprintf(w, "couldn't execute template")
}
}
func postComment(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(mux.Vars(r)["id"], 10, 64)
if err != nil {
slog.Error("Could not parse id", "error", err)
fmt.Fprintf(w, "ERROR! Could not get task ID from request")
return
}
err = r.ParseForm()
if err != nil {
slog.Error("Error parsing form", "error", err)
fmt.Fprintf(w, "<p>ERROR! Could not pase the form data</p>")
return
}
if r.FormValue("comments") == "" {
return
}
var pu *string
username := r.FormValue("username")
if username != "" {
pu = &username
}
if err := addComment(uint32(id), pu, r.FormValue("comments")); err != nil {
slog.Error("Could not save a new comment", "error", err)
fmt.Fprintf(w, "<p>ERROR! could not insert the comment into the DB</p>")
return
}
err = tmpl.ExecuteTemplate(
w,
"make-comment.html",
Comment{TaskID: uint32(id), User: pu, Content: r.FormValue("comments"), CreatedAt: time.Now()},
)
if err != nil {
slog.Error("could not render template for new comment", "error", err)
}
}
func displayTaskImages(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(mux.Vars(r)["id"], 10, 64)
if err != nil {
slog.Error("Could not parse id", "err", err)
fmt.Fprintf(w, "ERROR! Could not get task ID from request")
return
}
paths, err := getTaskImages(uint32(id))
if err != nil {
slog.Error("could not get image paths", "task", id, "err", err)
fmt.Fprintf(w, "ERROR! Could not get images for task %d", id)
return
}
if len(paths) == 0 {
return
}
//TODO: Move to a template so tailwind will find the css classes
content := ""
for _, p := range paths {
content += fmt.Sprintf(`<img onclick="enlargeModal()" class="h-32 w-32 mx-5 border-2 border-sky-900 cursor-pointer" src="%s" alt="task-image" width="128" height="128">`, p)
}
//This script is defiend in src/showTask.js, it adds a listener to each image
content += `<script src="/static/enlargeImages.js"></script>`
fmt.Fprintf(w, content)
}
func notFound(w http.ResponseWriter, r *http.Request) {
s := fmt.Sprintf("<h2>404 Could not find!</h2><p>Path Provided: %s</p>", r.URL)
fmt.Fprintf(w, s)
}
func NewServer() *mux.Router {
//Setup the templates so the endpoints work
tmpl = template.Must(template.ParseGlob("templates/*.html"))
mux := mux.NewRouter()
mux.HandleFunc("/", index).Methods("GET")
mux.HandleFunc("/prod", index).Methods("GET")
mux.HandleFunc("/prod/goodidea", index).Methods("GET")
mux.HandleFunc("/tasks", listTasks).Methods("GET")
mux.HandleFunc("/tasks", createTask).Methods("POST")
mux.HandleFunc("/tasks/{id}", viewTask).Methods("GET")
mux.HandleFunc("/tasks/{id}/score", updateScore).Methods("POST")
mux.HandleFunc("/tasks/{id}/comments", postComment).Methods("POST")
mux.HandleFunc("/tasks/{id}/complete", markTaskComplete).Methods("POST")
mux.HandleFunc("/tasks/{id}/images", displayTaskImages).Methods("GET")
//static assets that are generated like CSS and JavaScript
s := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))
mux.PathPrefix("/static/").Handler(s)
//serve static files from go generate
mux.PathPrefix("/login").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./pages/login.html")
})
//serve static files from go generate
mux.PathPrefix("/signup").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./pages/signup.html")
})
mux.NotFoundHandler = http.HandlerFunc(notFound)
return mux
}