-
Notifications
You must be signed in to change notification settings - Fork 1
/
route_thread.go
97 lines (88 loc) · 2.31 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
89
90
91
92
93
94
95
96
97
package main
import (
"github.com/anuragdhingra/lets-chat/data"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
"strconv"
)
type ThreadInfoPublic struct {
Thread data.Thread
CreatedBy data.User
Posts []PostInfoPublic
}
type ThreadInfoPrivate struct {
Thread data.Thread
CreatedBy data.User
User data.User
Posts []PostInfoPublic
}
func NewThread(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
sess, err := session(w, r)
if err == nil {
loggedInUser, err := sess.User()
data := ThreadsInfoPrivate{nil, loggedInUser}
if err != nil {
log.Print(err)
return
} else {
generateHTML(w, data, "layout", "private.navbar", "new.thread")
}
} else {
log.Print(err)
http.Redirect(w, r, "/login", http.StatusFound)
return
}
}
func CreateThread(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
err := r.ParseForm()
throwError(err)
sess, err := session(w, r)
throwError(err)
user, err := sess.User()
throwError(err)
createThreadRequest := data.CreateThreadRequest{
r.PostFormValue("topic"),
user.Id,
}
threadId, err := createThreadRequest.Create()
log.Print(threadId)
throwError(err)
url := "/threads/" + strconv.Itoa(threadId)
log.Print(url)
http.Redirect(w, r, url, http.StatusFound)
}
func FindThread(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
threadId := p.ByName("id")
thread, err := data.ThreadByID(threadId)
if err != nil {
log.Print(err)
return
} else {
user, err := data.UserById(thread.UserId)
throwError(err)
posts, err := data.PostsByThreadId(thread.Id)
throwError(err)
postList := CreatePostList(posts)
sess, err := session(w, r)
if err != nil {
data := ThreadInfoPublic{thread, user, postList}
generateHTML(w, data, "layout","public.navbar", "public.thread")
} else {
loggedInUser, err := sess.User()
throwError(err)
data := ThreadInfoPrivate{thread, user, loggedInUser, postList}
generateHTML(w, data, "layout", "private.navbar","private.thread")
}
}
}
func CreateThreadList(threads []data.Thread) (threadListPublic []ThreadInfoPublic) {
for _, thread := range threads {
threadUserId := thread.UserId
user, err := data.UserById(threadUserId)
throwError(err)
threadInfoPublic := ThreadInfoPublic{thread,user, nil}
threadListPublic = append(threadListPublic, threadInfoPublic)
}
return
}