-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
166 lines (143 loc) · 3.99 KB
/
main.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
package main
import (
"embed"
"encoding/json"
"flag"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"io/fs"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"text/template"
)
type moodOperatorStruct struct {
Username string `json:"username"`
Mood string `json:"mood"`
Operation string `json:"operation"`
Room string `json:"string"`
}
var (
clients = make(map[Client]bool)
broadcast = make(chan *moodOperatorStruct)
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
db = Database()
port = flag.String("port", "8844", "port to listen on")
)
type Client struct {
Room string
Client *websocket.Conn
}
type App struct {
Port string
Logf func(string, ...interface{})
}
//go:embed index.html
var index string
//go:embed room.html
var room string
//go:embed assets/*
var assets embed.FS
func main() {
flag.Parse()
app := App{
Port: *port,
}
port := os.Getenv("PORT")
if port != "" {
app.Port = port
}
router := mux.NewRouter()
router.StrictSlash(true)
router.HandleFunc("/", rootHandler).Methods("GET")
router.HandleFunc("/{room:[0-9]+}", roomHandler).Methods("GET")
router.HandleFunc("/{room:[0-9]+}/mood", addMoodHandler).Methods("POST")
router.HandleFunc("/{room:[0-9]+}/ws", wsHandler)
router.HandleFunc("/{room:[0-9]+}/all", allHandler).Methods("GET")
router.HandleFunc("/{room:[0-9]+}/delete", deleteMoodHandler).Methods("POST")
router.PathPrefix("/assets/").Handler(assetsHandler())
go echo()
log.Printf("Now open http://localhost:%s", app.Port)
addr := net.JoinHostPort("", app.Port)
log.Fatal(http.ListenAndServe(addr, router))
}
func assetsHandler() http.Handler {
fsys := fs.FS(assets)
contentStatic, _ := fs.Sub(fsys, "assets")
return http.StripPrefix("/assets/", http.FileServer(http.FS(contentStatic)))
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.New("template").Delims("[[", "]]").Parse(index))
footer, _ := ioutil.ReadFile("footer.html")
tmpl.Execute(w, string(footer))
}
func roomHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.New("template").Delims("[[", "]]").Parse(room))
footer, _ := ioutil.ReadFile("footer.html")
tmpl.Execute(w, string(footer))
}
func writer(mood *moodOperatorStruct) {
broadcast <- mood
}
func addMoodHandler(w http.ResponseWriter, r *http.Request) {
var mood UserMoodStruct
if err := json.NewDecoder(r.Body).Decode(&mood); err != nil {
log.Printf("ERROR: %s", err)
http.Error(w, "Bad request", http.StatusTeapot)
return
}
Save(mood, db)
defer r.Body.Close()
go writer(&moodOperatorStruct{Username: mood.Username, Mood: mood.Mood, Operation: "Save", Room: mood.Room})
}
func deleteMoodHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var mood UserMoodStruct
if err := json.NewDecoder(r.Body).Decode(&mood); err != nil {
log.Printf("ERROR: %s", err)
http.Error(w, "Bad request", http.StatusTeapot)
return
}
Delete(mood.RoomUser, db)
defer r.Body.Close()
go writer(&moodOperatorStruct{Username: mood.Username, Mood: mood.Mood, Operation: "Delete", Room: vars["room"]})
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
// register client
clients[Client{Client: ws, Room: vars["room"]}] = true
}
func allHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
userMoods := GetAll(vars["room"], db)
json.NewEncoder(w).Encode(userMoods)
}
func echo() {
for {
val := <-broadcast
mood, _ := json.Marshal(val)
// @TODO there's probably a better way of only sending to clients in the current room
for client := range clients {
if client.Room == val.Room {
err := client.Client.WriteMessage(websocket.TextMessage, mood)
if err != nil {
log.Printf("Websocket error: %s", err)
client.Client.Close()
delete(clients, client)
}
}
}
}
}