This repository has been archived by the owner on Aug 12, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
300 lines (260 loc) · 6.65 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
package main
/*
* backend for simple social network
*/
import (
rdb "./db"
"github.com/slmyers/go-json-rest/rest"
"log"
"net/http"
"net/url"
"sort"
"strconv"
"time"
)
func main() {
i := Impl{}
i.InitDB()
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
// declare the handlers for various requests
router, err := rest.MakeRouter(
rest.Post("/user", i.CreateUser),
rest.Post("/status", i.PostStatus),
rest.Post("/follow", i.FollowUser),
rest.Post("/unfollow", i.UnfollowUser),
rest.Get("/timeline", i.GetTimeline),
rest.Get("/user", i.GetUser),
// uncomment if you would also like to serve files
//rest.Get("/", homeHandler),
)
if err != nil {
log.Fatal(err)
}
api.SetApp(router)
log.Fatal(http.ListenAndServe(":8000", api.MakeHandler()))
}
/* this is included as an example of how to serve files (webpages)*/
func homeHandler(w rest.ResponseWriter, r *rest.Request) {
http.ServeFile(w.(http.ResponseWriter), r.Request,
r.URL.Path[1:])
}
type Impl struct {
DB *rdb.DB
}
func (i *Impl) InitDB() {
i.DB = rdb.NewDB("localhost:6379")
if i.DB == nil {
log.Fatal("i.DB is nil")
}
}
/*
* consumes JSON of the form:
* {
* "username": "<username>",
* "name": "<users' name>"
* }
*/
func (i *Impl) CreateUser(w rest.ResponseWriter, r *rest.Request) {
var user UserPayload
err := r.DecodeJsonPayload(&user)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// returns -1 if username is unable to be registered, ie, already taken
uid, err := i.DB.CreateUser(user.Username, user.Name)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if uid == -1 {
w.WriteJson(map[string]string{
"uid": strconv.Itoa(uid),
"user": "unable to create",
})
return
}
userOut, err := i.DB.GetUser(uid)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&userOut)
}
/*
* consumes JSON of the form
{
"uid": <user id>
"msg": <text string containing message>
}
*/
func (i *Impl) PostStatus(w rest.ResponseWriter, r *rest.Request) {
var status StatusPayload
if err := r.DecodeJsonPayload(&status); err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
sid, err := i.DB.PostStatus(status.Uid, status.Msg)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
post, err := i.DB.GetStatus(sid)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&post)
}
/*
* handles requests of form /follow?uid=2&otherId=3
*/
func (i *Impl) FollowUser(w rest.ResponseWriter, r *rest.Request) {
v, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
uid, err := strconv.Atoi(v.Get("uid"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
otherId, err := strconv.Atoi(v.Get("otherId"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
res, err := i.DB.Follow(uid, otherId)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if res == true {
w.WriteJson(map[string]string{"following": v.Get("otherId"),
"follower": v.Get("uid"), "followed": "true"})
} else {
w.WriteJson(map[string]string{"following": v.Get("otherId"),
"follower": v.Get("uid"), "followed": "false"})
}
}
/*
* handles requests of form /unfollow?uid=2&otherId=3
*/
func (i *Impl) UnfollowUser(w rest.ResponseWriter, r *rest.Request) {
v, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
uid, err := strconv.Atoi(v.Get("uid"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
otherId, err := strconv.Atoi(v.Get("otherId"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
res, err := i.DB.Unfollow(uid, otherId)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if res == true {
w.WriteJson(map[string]string{"following": v.Get("otherId"),
"follower": v.Get("uid"), "unfollowed": "true"})
} else {
w.WriteJson(map[string]string{"following": v.Get("otherId"),
"follower": v.Get("uid"), "unfollowed": "false"})
}
}
/*
* handles requests of the form /timeline?uid=7&page=1
*/
func (i *Impl) GetTimeline(w rest.ResponseWriter, r *rest.Request) {
v, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
uid, err := strconv.Atoi(v.Get("uid"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
page, err := strconv.Atoi(v.Get("page"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
res, err := i.DB.GetUserTimeline(uid, page, 30)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
output := new(TimelineResponse)
output.Posts = make([]rdb.Status, len(res))
output.Uid = uid
output.Page = page
outputIndex := 0
// channel to send/recieve status structs
statuses := make(chan rdb.Status)
defer close(statuses)
var pst int
for j := 0; j < len(res); j++ {
pst = res[j]
// anon goroutine to get a status in timeline page
// this means that all statuses are fetched concurrently
go func(post int) {
status, err := i.DB.GetStatus(post)
if err != nil {
log.Printf("error getting post %d, %v\n", post, err)
return
}
// pipe the fetched status into the channel previously made
statuses <- status
}(pst)
}
// this code is blocking
Loop:
for outputIndex < len(res) {
select {
case sts := <-statuses:
output.Posts[outputIndex] = sts
outputIndex++
case <-time.After(time.Second * 1):
log.Printf("timeout getting timeline:%d page:%d\n", uid,
page)
break Loop
}
}
// because the statuses were retrieved concurrently we can't be sure
// of what order they will appear in output.Posts, so we must sort them
// if we want them to appear from newest to oldest
sort.Sort(output.Posts)
w.WriteJson(&output)
}
/*
* handles requests of the form /user?uid=7
*/
func (i *Impl) GetUser(w rest.ResponseWriter, r *rest.Request) {
v, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
uid, err := strconv.Atoi(v.Get("uid"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
usr, err := i.DB.GetUser(uid)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&usr)
}