/
handlers.go
executable file
·104 lines (95 loc) · 2.08 KB
/
handlers.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
package chat
import (
"encoding/json"
"net/http"
"fmt"
"google.golang.org/appengine"
"google.golang.org/appengine/channel"
"google.golang.org/appengine/user"
)
// API handles api calls
type API struct {
root string
}
// NewAPI creates a new API, root should be set to the root url for the API
func NewAPI(root string) *API {
api := &API{
root: root,
}
return api
}
func (api *API) ServeHTTP(res http.ResponseWriter, req *http.Request) {
endpoint := req.URL.Path[len(api.root):]
method := req.Method
var err error
switch endpoint {
case "channels":
switch method {
case "POST":
err = api.handlePostChannel(res, req)
default:
http.Error(res, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
case "messages":
switch method {
case "POST":
err = api.handlePostMessage(res, req)
default:
http.Error(res, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
default:
http.NotFound(res, req)
return
}
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(res).Encode(err.Error())
}
}
// create the channel
func (api *API) handlePostChannel(res http.ResponseWriter, req *http.Request) error {
ctx := appengine.NewContext(req)
u := user.Current(ctx)
tok, err := channel.Create(ctx, u.Email)
if err != nil {
return err
}
room, err := getRoom(ctx)
if err != nil {
return err
}
room.Emails = append(room.Emails, u.Email)
err = putRoom(ctx, room)
if err != nil {
return err
}
json.NewEncoder(res).Encode(tok)
return nil
}
func (api *API) handlePostMessage(res http.ResponseWriter, req *http.Request) error {
ctx := appengine.NewContext(req)
type Message struct {
Text string
}
var message Message
err := json.NewDecoder(req.Body).Decode(&message)
if err != nil {
return err
}
fmt.Println("***********IS THE MESSAGE HERE: ", message)
// u.Email == "test@example.com"
room, err := getRoom(ctx)
if err != nil {
return err
}
for _, email := range room.Emails {
err = channel.SendJSON(ctx, email, message)
if err != nil {
return err
}
}
json.NewEncoder(res).Encode(true)
return nil
}