forked from tada-team/nane
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
67 lines (59 loc) · 1.58 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
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/tada-team/nane/nane"
)
func settingsHandler(w http.ResponseWriter, r *http.Request) error {
return jsonResponse(w, nane.ApiResponse{
Result: nane.Settings{
MaxMessageLength: settings.GetMaxMessageLength(),
MaxRoomTitleLength: settings.GetMaxRoomTitleLength(),
MaxUsernameLength: settings.GetMaxUsernameLength(),
Uptime: time.Since(start),
},
})
}
func roomsHandler(w http.ResponseWriter, r *http.Request) error {
return jsonResponse(w, nane.ApiResponse{
Result: getRooms(),
})
}
func roomHandler(w http.ResponseWriter, r *http.Request) error {
name := mux.Vars(r)["name"]
room := getRoom(name)
if room == nil {
w.WriteHeader(http.StatusNotFound)
return jsonResponse(w, nane.ApiResponse{
Error: fmt.Sprintf("room %s not found", name),
})
}
return jsonResponse(w, nane.ApiResponse{
Result: room,
})
}
func historyHandler(w http.ResponseWriter, r *http.Request) error {
name := mux.Vars(r)["name"]
room := getRoom(name)
if room == nil {
w.WriteHeader(http.StatusNotFound)
return jsonResponse(w, nane.ApiResponse{
Error: fmt.Sprintf("room %s not found", name),
})
}
return jsonResponse(w, nane.ApiResponse{
Result: room.getMessages(),
})
}
func jsonResponse(w http.ResponseWriter, v nane.ApiResponse) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
encoder := json.NewEncoder(w)
if err := encoder.Encode(v); err != nil {
return errors.Wrap(err, "encode fail")
}
return nil
}