-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute_thread.go
88 lines (83 loc) · 2.29 KB
/
route_thread.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
package main
import (
"chitchat/data"
"fmt"
"net/http"
)
// GET /threads/new
// Show the new thread form page
func newThread(writer http.ResponseWriter, request *http.Request) {
_, err := session(writer, request)
if err != nil {
http.Redirect(writer, request, "/login", 302)
} else {
generateHTML(writer, nil, "layout", "private.navbar", "new.thread")
}
}
// POST /signup
// Create the user account
func createThread(writer http.ResponseWriter, request *http.Request) {
sess, err := session(writer, request)
if err != nil {
http.Redirect(writer, request, "/login", 302)
} else {
err = request.ParseForm()
if err != nil {
danger(err, "Cannot parse form")
}
user, err := sess.User()
if err != nil {
danger(err, "Cannot get user from session")
}
topic := request.PostFormValue("topic")
if _, err := user.CreateThread(topic); err != nil {
danger(err, "Cannot create thread")
}
http.Redirect(writer, request, "/", 302)
}
}
// GET /thread/read
// Show the details of the thread, including the posts and the form to write a post
func readThread(writer http.ResponseWriter, request *http.Request) {
vals := request.URL.Query()
uuid := vals.Get("id")
thread, err := data.ThreadByUUID(uuid)
if err != nil {
error_message(writer, request, "Cannot read thread")
} else {
_, err := session(writer, request)
if err != nil {
generateHTML(writer, &thread, "layout", "public.navbar", "public.thread")
} else {
generateHTML(writer, &thread, "layout", "private.navbar", "private.thread")
}
}
}
// POST /thread/post
// Create the post
func postThread(writer http.ResponseWriter, request *http.Request) {
sess, err := session(writer, request)
if err != nil {
http.Redirect(writer, request, "/login", 302)
} else {
err = request.ParseForm()
if err != nil {
danger(err, "Cannot parse form")
}
user, err := sess.User()
if err != nil {
danger(err, "Cannot get user from session")
}
body := request.PostFormValue("body")
uuid := request.PostFormValue("uuid")
thread, err := data.ThreadByUUID(uuid)
if err != nil {
error_message(writer, request, "Cannot read thread")
}
if _, err := user.CreatePost(thread, body); err != nil {
danger(err, "Cannot create post")
}
url := fmt.Sprint("/thread/read?id=", uuid)
http.Redirect(writer, request, url, 302)
}
}