/
api.go
101 lines (82 loc) · 2.57 KB
/
api.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
package main
import (
"fmt"
"net/http"
"strconv"
"github.com/ant0ine/go-json-rest/rest"
)
// APIIndex is status function
func APIIndex(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson("Welcome!\n")
}
// APIDialogIndex is used to get dialogs index
func (i *Impl) APIDialogIndex(w rest.ResponseWriter, r *rest.Request) {
userID := r.PathParam("user_id")
page, err := strconv.Atoi(r.FormValue("page"))
offset := 0
if err == nil {
offset = (page - 1) * 10
}
dialogs := i.GetDialogs(userID, offset)
w.WriteJson(&dialogs)
}
// APIDialogShow is used to show dialog for RAILS
func (i *Impl) APIDialogShow(w rest.ResponseWriter, r *rest.Request) {
userID := r.PathParam("user_id")
dialogID, _ := strconv.Atoi(r.PathParam("dialog_id"))
dialog := i.ShowDialog(userID, dialogID)
w.WriteJson(&dialog)
}
// APIMessageIndex is used to show dialog messages
func (i *Impl) APIMessageIndex(w rest.ResponseWriter, r *rest.Request) {
userID := r.PathParam("user_id")
dialogID, _ := strconv.Atoi(r.PathParam("dialog_id"))
page, err := strconv.Atoi(r.FormValue("page"))
offset := 0
if err == nil {
offset = (page - 1) * 10
}
messages := i.IndexMessages(userID, dialogID, offset)
w.WriteJson(&messages)
}
// APIUserShow returns number of unread dialogs
func (i *Impl) APIUserShow(w rest.ResponseWriter, r *rest.Request) {
userID := r.PathParam("user_id")
user := i.ShowUser(userID)
w.WriteJson(&user)
}
// APIDialogCreate is used to create dialog and message
func (i *Impl) APIDialogCreate(w rest.ResponseWriter, r *rest.Request) {
userID := r.PathParam("user_id")
params := DialogCreateJSON{}
if err := r.DecodeJsonPayload(¶ms); err != nil {
fmt.Println("error decoding json: ", err)
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dialog, err := i.CreateDialog(userID, params)
if err != nil {
fmt.Println("error creating dialog: ", err)
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&dialog)
}
// APIMessageCreate creates message for dialog
func (i *Impl) APIMessageCreate(w rest.ResponseWriter, r *rest.Request) {
userID := r.PathParam("user_id")
dialogID, _ := strconv.Atoi(r.PathParam("dialog_id"))
message := Message{}
if err := r.DecodeJsonPayload(&message); err != nil {
fmt.Println("error decoding json: ", err)
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
message, err := i.CreateMessage(userID, dialogID, message)
if err != nil {
fmt.Println("error creating message: ", err)
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&message)
}